unit WinCGRegMain;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Mask, RzEdit, RzDBEdit, DBCtrls, RzDBCmbo, ComCtrls,
  RzDTP, RzDBDTP, DB, ADODB, BetterADODataSet, Grids,  AdvGrid,
  RzGroupBar, RzTabs, ExtCtrls, RzPanel, DBGrids, RzDBGrid, dxCore,
  dxButton, RzButton, RzLabel, QRCtrls, jpeg, QuickRpt, QRPDFFilt,Global,
  gtPDFDoc, gtPDFCrypt, gtClasses, gtCstPDFDoc, gtExPDFDoc, gtExProPDFDoc,BaseGrid,
  Menus, TFlatButtonUnit, RzCmboBx, RzBorder, AdvPicture, datelbl, RzStatus,StrUtils,
  RzShellDialogs,DateUtils,Winsock,IniFiles, RzRadChk, RzDBChk, RzBckgnd,
  RzSpnEdt, RzTrkBar, ImgList, RzLstBox, RzListVw, RzCommon, RzBtnEdt,
  RzRadGrp, RzChkLst, RzSndMsg;

type

  TStaffObj = class(TObject)
    StaffKey: Integer;
    Name: string;
    Branch: string;
    Department: string;
  end;
  TDropDownListObj = class(TObject)
    PK: Integer;
    StringName: string;
    FltAmount:variant;
  end;
  TUserRightsObj = class(TObject)
    URKey: Integer;
    EmpCode: Integer;    
    ModuleName: string;
    CAdd:string;
    CEdit:string;
    CDelete:string;
    CSave:string;
    CPrint:string;
  end;


  TfrmRegistrationMain = class(TForm)
    adoConn: TADOConnection;
    adoReviewerTable: TBetterADODataSet;
    dsSchoolList: TDataSource;
    adoSchoolList: TBetterADODataSet;
    adoRankList: TBetterADODataSet;
    dsRankList: TDataSource;
    adoShippingList: TBetterADODataSet;
    dsShippingList: TDataSource;
    adoEndorserList: TBetterADODataSet;
    dsEndorserList: TDataSource;
    dsReviewerTable: TDataSource;
    RzPanel3: TRzPanel;
    RzPageControl1: TRzPageControl;
    TabSheet1: TRzTabSheet;
    RzPanel1: TRzPanel;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    Label6: TLabel;
    Label7: TLabel;        { TODO : billing }
    Label8: TLabel;
    Label9: TLabel;
    Label14: TLabel;
    Label17: TLabel;
    edtFirstname: TRzDBEdit;
    edtLastname: TRzDBEdit;
    edtMiddlename: TRzDBEdit;
    edtAddress: TRzDBMemo;
    edtEmail: TRzDBEdit;
    edtMobile: TRzDBEdit;
    RzDBEdit7: TRzDBEdit;
    cbSchool: TRzDBLookupComboBox;
    cbShipping: TRzDBLookupComboBox;
    edtRemarks: TRzDBMemo;
    cbRank: TRzDBLookupComboBox;
    cbEndorser: TRzDBLookupComboBox;
    dtDateEnroll: TRzDBDateTimePicker;
    Button1: TButton;
    Button3: TButton;
    Button2: TButton;
    TabSheet2: TRzTabSheet;
    RzPanel2: TRzPanel;
    adoReviewerList: TBetterADODataSet;
    dsReviewerList: TDataSource;
    TabSheet3: TRzTabSheet;
    Label18: TLabel;
    Label19: TLabel;
    RzDBMemo1: TRzDBMemo;
    RzDBEdit1: TRzDBEdit;
    dxButton1: TdxButton;
    dxButton2: TdxButton;
    dxButton3: TdxButton;
    dxButton4: TdxButton;
    pnlQuickAdd: TRzPanel;
    RzGroupBox1: TRzGroupBox;
    edtName: TRzEdit;
    RzButton1: TRzButton;
    RzButton2: TRzButton;
    RzButton3: TRzButton;
    pnlQuickPayment: TRzPanel;
    RzGroupBox2: TRzGroupBox;
    edtPaidRemarks: TRzEdit;
    RzButton5: TRzButton;
    RzButton6: TRzButton;
    edtDatePaid: TRzDateTimeEdit;
    edtAmtPaid: TRzNumericEdit;
    RzLabel1: TRzLabel;
    RzLabel2: TRzLabel;
    RzLabel3: TRzLabel;
    grdPaymentSummary: TAdvStringGrid;
    Label10: TLabel;
    Button4: TButton;
    RzDBNumericEdit1: TRzDBNumericEdit;
    edtARNumber: TRzEdit;
    RzLabel4: TRzLabel;
    QuickRep1: TQuickRep;
    PageHeaderBand1: TQRBand;
    QRImage1: TQRImage;
    QRLabel1: TQRLabel;
    QRLabel7: TQRLabel;
    QRLabel9: TQRLabel;
    lblReviewerID: TQRLabel;
    DetailBand1: TQRBand;
    QRShape5: TQRShape;
    QRLabel4: TQRLabel;
    QRLabel2: TQRLabel;
    QRLabel8: TQRLabel;
    QRLabel6: TQRLabel;
    QRLabel3: TQRLabel;
    QRShape1: TQRShape;
    QRLabel5: TQRLabel;
    QRBand1: TQRBand;
    QRLabel11: TQRLabel;
    QRLabel10: TQRLabel;
    lblRemarks: TQRLabel;
    QRShape2: TQRShape;
    lblEOff: TQRLabel;
    dsPaymentDetails: TDataSource;
    adoPaymentDetails: TBetterADODataSet;
    gtPDFDocument1: TgtPDFDocument;
    QRDBText6: TQRDBText;
    QRDBText1: TQRDBText;
    QRLabel14: TQRLabel;
    QRShape4: TQRShape;
    QRShape3: TQRShape;
    QRShape6: TQRShape;
    QRBand2: TQRBand;
    QRShape7: TQRShape;
    QRShape8: TQRShape;
    QRDBText2: TQRDBText;
    QRDBText3: TQRDBText;
    lblShipping: TQRLabel;
    lblSchool: TQRLabel;
    lblEndorsed: TQRLabel;
    lblFee: TQRLabel;
    QRDBText4: TQRDBText;
    lblDate: TQRLabel;
    QRShape9: TQRShape;
    QRShape10: TQRShape;
    QRLabel16: TQRLabel;
    QRLabel17: TQRLabel;
    QRLabel18: TQRLabel;
    QRDBText7: TQRDBText;
    Label11: TLabel;
    PopupMenu1: TPopupMenu;
    OpenPayment1: TMenuItem;
    RemovePayment1: TMenuItem;
    NewPayment1: TMenuItem;
    edtPaymentKey: TRzEdit;
    edtCurrBalance: TRzNumericEdit;
    RzLabel5: TRzLabel;
    QRLabel15: TQRLabel;
    QRDBText5: TQRDBText;
    TabSheet4: TRzTabSheet;
    adoReportsList: TBetterADODataSet;
    dsReportList: TDataSource;
    QuickRep2: TQuickRep;
    QRBand3: TQRBand;
    QRBand4: TQRBand;
    QRLabel19: TQRLabel;
    QRDBText8: TQRDBText;
    QRLHeader: TQRLabel;
    QRDBText9: TQRDBText;
    QRShape11: TQRShape;
    QRLabel21: TQRLabel;
    QRLabel22: TQRLabel;
    QRLabel23: TQRLabel;
    QRLabel24: TQRLabel;
    QRLabel25: TQRLabel;
    QRLabel26: TQRLabel;
    QRLabel27: TQRLabel;
    QRLabel28: TQRLabel;
    QRLabel29: TQRLabel;
    QRLabel30: TQRLabel;
    QRLabel31: TQRLabel;
    QRDBText10: TQRDBText;
    QRDBText11: TQRDBText;
    QRDBText12: TQRDBText;
    QRDBText13: TQRDBText;
    QRBand5: TQRBand;
    QRExpr1: TQRExpr;
    QRShape12: TQRShape;
    Button5: TButton;
    edtEnrollOfficer: TRzEdit;
    Label15: TLabel;
    TabSheet5: TRzTabSheet;
    adqTemp: TADOQuery;
    Button6: TButton;
    TabSheet6: TRzTabSheet;
    Button7: TButton;
    RzProgressStatus1: TRzProgressStatus;
    AdvStringGrid1: TAdvStringGrid;
    RzButton4: TRzButton;
    RzOpenDialog1: TRzOpenDialog;
    PopupMenu2: TPopupMenu;
    NewReviewee1: TMenuItem;
    QRLFilter: TQRLabel;
    QRLReportingDate: TQRLabel;
    RzPanel4: TRzPanel;
    RzGroupBox4: TRzGroupBox;
    RzLabel18: TRzLabel;
    edtFilterName: TRzEdit;
    edtFilterDateStart: TRzDateTimePicker;
    RzLabel20: TRzLabel;
    edtFilterDateEnd: TRzDateTimePicker;
    RzLabel21: TRzLabel;
    edtFilterComp: TRzEdit;
    RzLabel22: TRzLabel;
    edtFilterSchool: TRzEdit;
    btnFilter: TRzBitBtn;
    RzLabel23: TRzLabel;
    edtChargeTo: TRzComboBox;
    QRLabel13: TQRLabel;
    QRLabel20: TQRLabel;
    lblPrinted: TQRLabel;
    lblChargeTo: TQRLabel;
    pageSearchResults: TRzPageControl;
    tabSheetReviewee: TRzTabSheet;
    tabSheetEndorsement: TRzTabSheet;
    gridReviewerList: TRzDBGrid;
    gridEndorsements: TAdvStringGrid;
    btnCreateEndorsement: TButton;
    pnlEndorsetoBranch: TRzPanel;
    groupboxEndHist: TRzGroupBox;
    RzLabel25: TRzLabel;
    RzLabel26: TRzLabel;
    RzLabel29: TRzLabel;
    edtEndHistRemarks: TRzEdit;
    edtEndHistDate: TRzDateTimeEdit;
    edtEndHistToBranch: TRzComboBox;
    btnCreateEndHist: TRzButton;
    RzButton8: TRzButton;
    edtEndHistKey: TRzEdit;
    Timer1: TTimer;
    Label16: TLabel;
    RzDBLookupComboBox1: TRzDBLookupComboBox;
    adoSatBranchList: TBetterADODataSet;
    dsSatBranchList: TDataSource;
    lblSatBranch: TQRLabel;
    TabSheet7: TRzTabSheet;
    Prepare1: TMenuItem;
    TabSheet8: TRzTabSheet;
    AdvStringGrid3: TAdvStringGrid;
    cbStatus: TRzDBComboBox;
    rzGrpContacts: TRzGroupBox;
    Label12: TLabel;
    edtContact: TRzDBEdit;
    Label13: TLabel;
    edtContactNumber: TRzDBEdit;
    rzGrpInclusions: TRzGroupBox;
    RzDBCheckBox1: TRzDBCheckBox;
    RzDBCheckBox2: TRzDBCheckBox;
    RzDBCheckBox4: TRzDBCheckBox;
    RzDBCheckBox3: TRzDBCheckBox;
    RzDBCheckBox5: TRzDBCheckBox;
    RzDBCheckBox6: TRzDBCheckBox;
    RzDBCheckBox7: TRzDBCheckBox;
    RzDBCheckBox8: TRzDBCheckBox;
    RzDBCheckBox9: TRzDBCheckBox;
    RzDBCheckBox10: TRzDBCheckBox;
    RzDBCheckBox11: TRzDBCheckBox;
    RzDBCheckBox12: TRzDBCheckBox;
    RzDBCheckBox13: TRzDBCheckBox;
    RzDBCheckBox14: TRzDBCheckBox;
    QRLabel12: TQRLabel;
    lblInclusions: TQRLabel;
    RzLabel24: TRzLabel;
    cbFilterStatus: TRzComboBox;
    RzPanel5: TRzPanel;
    rzFilterStatusbar: TRzStatusPane;
    RzSeparator1: TRzSeparator;
    RzBitBtn1: TRzBitBtn;
    RzBitBtn3: TRzBitBtn;
    rzTrackCRPer: TRzTrackBar;
    RzLabel30: TRzLabel;
    rzSpinPerFrom: TRzSpinEdit;
    RzLabel31: TRzLabel;
    rzCreAmtFrom: TRzNumericEdit;
    RzLabel32: TRzLabel;
    rzLblOrigAmt: TRzLabel;
    rzBalAmt: TRzNumericEdit;
    RzLabel34: TRzLabel;
    RzLabel33: TRzLabel;
    RzLabel35: TRzLabel;
    rzMainEntFormStatusHints: TRzStatusPane;
    RzVersionInfo1: TRzVersionInfo;
    RzPanel6: TRzPanel;
    RzBorder2: TRzBorder;
    AdvPicture1: TAdvPicture;
    RzVersionInfoStatus1: TRzVersionInfoStatus;
    RzLabel15: TRzLabel;
    RzBorder1: TRzBorder;
    btnLogin: TFlatButton;
    btnCancel: TFlatButton;
    cboLogUser: TRzComboBox;
    RzLabel17: TRzLabel;
    RzLabel16: TRzLabel;
    cboLogBranch: TRzComboBox;
    RzPanel7: TRzPanel;
    RzPanel8: TRzPanel;
    RzPanel9: TRzPanel;
    RzPanel10: TRzPanel;
    RzVersionInfoStatus2: TRzVersionInfoStatus;
    main_rzPanelMainMenu: TRzPanel;
    main_rzStatusBarMain: TRzStatusBar;
    RzToolbar1: TRzToolbar;
    rzMainBtnRegister: TRzToolButton;
    MainMenu1: TMainMenu;
    PopupMenu3: TPopupMenu;
    ImageList1: TImageList;
    rzMainBtnSearch: TRzToolButton;
    rzMainBtnPrint: TRzToolButton;
    rzMainBtnBilling: TRzToolButton;
    rzMainBtnRebates: TRzToolButton;
    rzMainBtnAdmin: TRzToolButton;
    rzMainBtnExit: TRzToolButton;
    rzMainBtnLogout: TRzToolButton;
    RzSpacer1: TRzSpacer;
    RzSpacer2: TRzSpacer;
    RzClockStatus1: TRzClockStatus;
    RzSeparator2: TRzSeparator;
    RzSeparator3: TRzSeparator;
    rzToolbarRegEntry: TRzToolbar;
    rzToolbarRegEntry_btnNew: TRzToolButton;
    rzToolbarRegEntry_btnPrint: TRzToolButton;
    rzToolbarRegEntry_btnSave: TRzToolButton;
    rzToolbarRegEntry_btnPayments: TRzToolButton;
    rzToolbarRegEntry_btnCreateEnd: TRzToolButton;
    rzListView_Endorsements: TRzListView;
    Label20: TLabel;
    Label21: TLabel;
    RzFrameController1: TRzFrameController;
    PopupMenu4: TPopupMenu;
    NewEndorsement1: TMenuItem;
    ReviewEndorsement1: TMenuItem;
    TabSheet9: TRzTabSheet;
    rzpnlMainBilling: TRzPanel;
    rzGrpBillTo: TRzGroupBox;
    rzFCBilling: TRzFrameController;
    rzbtneditSelectBillTo: TRzButtonEdit;
    rzmemoBillToName: TRzMemo;
    rzmemoBillToDetails: TRzMemo;
    rzcomboboxBillToDropdown: TRzComboBox;
    RzCheckGroup1: TRzCheckGroup;
    rzbitbtnBillToInfoButton: TRzBitBtn;
    rzGroupUpdateBillToInfo: TRzGroupBox;
    rzedtBillToInfoName: TRzEdit;
    rzedtBillToInfoAddress: TRzEdit;
    rzedtBillToInfoConPerson: TRzEdit;
    rzedtBillToInfoPosition: TRzEdit;
    RzLabel14: TRzLabel;
    RzLabel36: TRzLabel;
    RzLabel37: TRzLabel;
    RzLabel38: TRzLabel;
    rzedtBillToInfoMobile: TRzEdit;
    RzLabel39: TRzLabel;
    RzLabel40: TRzLabel;
    rzedtBillToInfoEmail: TRzEdit;
    RzLabel41: TRzLabel;
    rzedtBillToInfoOffNumber: TRzEdit;
    rzGroupParticulars: TRzGroupBox;
    rzeditPK: TRzEdit;
    RzPanel11: TRzPanel;
    RzBitBtn2: TRzBitBtn;
    rzchecklistReviewer: TRzCheckList;
    rzchkSelectAllParticulars: TRzCheckBox;
    RzBitBtn4: TRzBitBtn;
    RzGroupBox6: TRzGroupBox;
    RzEdit1: TRzEdit;
    RzGroupBox7: TRzGroupBox;
    RzEdit2: TRzEdit;
    TabSheet10: TRzTabSheet;
    RzPanel12: TRzPanel;
    v: TRzGroupBox;
    RzButtonEdit1: TRzButtonEdit;
    RzCheckGroup2: TRzCheckGroup;
    RzBitBtn5: TRzBitBtn;
    RzGroupBox9: TRzGroupBox;
    RzLabel42: TRzLabel;
    RzLabel43: TRzLabel;
    RzLabel44: TRzLabel;
    RzLabel45: TRzLabel;
    RzLabel46: TRzLabel;
    RzLabel47: TRzLabel;
    RzLabel48: TRzLabel;
    RzEdit3: TRzEdit;
    RzEdit4: TRzEdit;
    RzEdit5: TRzEdit;
    RzEdit6: TRzEdit;
    RzEdit7: TRzEdit;
    RzEdit8: TRzEdit;
    RzEdit9: TRzEdit;
    RzEdit10: TRzEdit;
    RzGroupBox10: TRzGroupBox;
    RzEdit11: TRzEdit;
    RzGroupBox11: TRzGroupBox;
    RzGroupBox12: TRzGroupBox;
    btnForRebatesPayment: TRzBitBtn;
    rzMainBtnPassers: TRzToolButton;
    RzSpacer3: TRzSpacer;
    TabSheet11: TRzTabSheet;
    rzpnlMainAdmin: TRzPanel;
    RzGroupBox14: TRzGroupBox;
    RzCheckGroup3: TRzCheckGroup;
    RzBitBtn7: TRzBitBtn;
    RzGroupBox15: TRzGroupBox;
    rzePK: TRzEdit;
    rzicbUserList: TRzImageComboBox;
    rzclAdminModuleList: TRzCheckList;
    RzGroupBox3: TRzGroupBox;
    RzLabel6: TRzLabel;
    RzLabel7: TRzLabel;
    RzLabel8: TRzLabel;
    RzLabel9: TRzLabel;
    RzLabel10: TRzLabel;
    RzLabel11: TRzLabel;
    RzLabel12: TRzLabel;
    RzLabel13: TRzLabel;
    RzLabel27: TRzLabel;
    RzLabel28: TRzLabel;
    edtFilterARFrom: TRzEdit;
    edtFilterDateFrom: TRzDateTimePicker;
    edtFilterDateTo: TRzDateTimePicker;
    edtFilterARTo: TRzEdit;
    edtFilterReviewer: TRzEdit;
    cboFilterBranch: TRzComboBox;
    cboFilterEndorser: TRzComboBox;
    cboFilterCompany: TRzComboBox;
    cboFilterStatus: TRzComboBox;
    edtFilterReportSchool: TRzEdit;
    FlatButton1: TFlatButton;
    FlatButton2: TFlatButton;
    FlatButton3: TFlatButton;
    grdReports: TRzDBGrid;
    QuickRep3: TQuickRep;
    QRBand6: TQRBand;
    QRLabel32: TQRLabel;
    QRLabel33: TQRLabel;
    QRLabel34: TQRLabel;
    QRLESREVID: TQRLabel;
    QRImage2: TQRImage;
    QRShape16: TQRShape;
    QRLESBRANCHNAME: TQRLabel;
    QRBand7: TQRBand;
    QRDBText16: TQRDBText;
    QRDBText17: TQRDBText;
    QRDBText18: TQRDBText;
    QRDBText19: TQRDBText;
    QRBand8: TQRBand;
    QRShape20: TQRShape;
    QRLESFOOTERENDORSEDBY: TQRLabel;
    QRLabel59: TQRLabel;
    QRLPRINTEDDATE: TQRLabel;
    QRLabel61: TQRLabel;
    QRLESINCLUSIONS: TQRLabel;
    QRBand9: TQRBand;
    QRShape22: TQRShape;
    QRLESBRANCHNAMEADD: TQRLabel;
    QRLabel64: TQRLabel;
    QRLabel65: TQRLabel;
    QRLabel66: TQRLabel;
    QRLabel67: TQRLabel;
    QRShape15: TQRShape;
    QRLESENROLLINGOFFICER: TQRLabel;
    QRLabel68: TQRLabel;
    QRLESFROMBRANCH: TQRLabel;
    QRLESTOBRANCH: TQRLabel;
    QRLESENDORSEDATE: TQRLabel;
    QRLESENDORSEMENTID: TQRLabel;
    QRDBText14: TQRDBText;
    QRLabel49: TQRLabel;
    QRLESEXAMFOR: TQRLabel;
    QRLabel51: TQRLabel;
    QRShape17: TQRShape;
    QRLabel37: TQRLabel;
    QRDBText15: TQRDBText;
    QRLabel38: TQRLabel;
    QRLESREVSHIPPING: TQRLabel;
    QRLESREVSCHOOL: TQRLabel;
    QRLabel39: TQRLabel;
    QRLabel40: TQRLabel;
    QRLESREVENDORSED: TQRLabel;
    QRLESCHARGETO: TQRLabel;
    QRLESREVIEWERFEE: TQRLabel;
    QRDBText20: TQRDBText;
    QRLabel35: TQRLabel;
    QRShape13: TQRShape;
    QRLESRECEIVEDBY: TQRLabel;
    QRLESFOOTERENDORSEDATE: TQRLabel;
    QRLESRECEIVEDDATE: TQRLabel;
    adoBilling: TBetterADODataSet;
    dsBilling: TDataSource;
    gridPassersResult: TAdvStringGrid;
    rzcbDateBetListTab: TRzCheckBox;
    Label23: TLabel;
    rzdatetimedatepass: TRzDBDateTimePicker;
    rzdatePasserslistBegin: TRzDateTimeEdit;
    rzdatePasserslistEnd: TRzDateTimeEdit;
    RzLabel19: TRzLabel;
    RzGroupBox5: TRzGroupBox;
    rzcPassersComlist: TRzComboBox;
    RzGroupBox8: TRzGroupBox;
    rzeditFullName: TRzEdit;
    RzCheckBox2: TRzCheckBox;
    RzPanel13: TRzPanel;
    RzGroupBox13: TRzGroupBox;
    RzGroupBox16: TRzGroupBox;
    gridRebatesForPayment: TAdvStringGrid;
    RzGroupBox17: TRzGroupBox;
    gridRebatesHistory: TAdvStringGrid;
    RzGroupBox18: TRzGroupBox;
    rzcomboPassersBRanch: TRzComboBox;
    rzcbSelectAllPassers: TRzCheckBox;
    rzcbPassersForRebates: TRzCheckBox;
    RzBitBtn6: TRzBitBtn;
    RzBitBtn8: TRzBitBtn;
    btn_processRebates: TRzBitBtn;
    RzBitBtn10: TRzBitBtn;
    QuickRep4: TQuickRep;
    QRBand10: TQRBand;
    QRLabel41: TQRLabel;
    QRLabel42: TQRLabel;
    QRLabel45: TQRLabel;
    QRLabel47: TQRLabel;
    QRLabel50: TQRLabel;
    QRBand11: TQRBand;
    QRShape19: TQRShape;
    QRDBText24: TQRDBText;
    QRDBText25: TQRDBText;
    QRDBText26: TQRDBText;
    QRDBText27: TQRDBText;
    QRBand12: TQRBand;
    QRShape21: TQRShape;
    QRLabel78: TQRLabel;
    QRLabel79: TQRLabel;
    QRLabel80: TQRLabel;
    QRLabel81: TQRLabel;
    QRLabel82: TQRLabel;
    QRShape23: TQRShape;
    QRLabel83: TQRLabel;
    QRLabel84: TQRLabel;
    QRLabel85: TQRLabel;
    QRBand13: TQRBand;
    QRShape24: TQRShape;
    QRImage3: TQRImage;
    QRLabel43: TQRLabel;
    QRLabel36: TQRLabel;
    QRShape18: TQRShape;
    QRLabel44: TQRLabel;
    QRLabel46: TQRLabel;
    QRLabel48: TQRLabel;
    QRLabel52: TQRLabel;
    QRShape14: TQRShape;
    QRLabel53: TQRLabel;
    RzSendMessage1: TRzSendMessage;
    QuickRep5: TQuickRep;
    QRBand14: TQRBand;
    QRBand15: TQRBand;
    QRDBText21: TQRDBText;
    QRDBText22: TQRDBText;
    QRDBText23: TQRDBText;
    QRDBText28: TQRDBText;
    QRDBText29: TQRDBText;
    QRDBText30: TQRDBText;
    QRBand16: TQRBand;
    RzBitBtn9: TRzBitBtn;
    procedure Button1Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure gridReviewerListDblClick(Sender: TObject);
    procedure dxButton1Click(Sender: TObject);
    procedure dxButton2Click(Sender: TObject);
    procedure dxButton3Click(Sender: TObject);
    procedure dxButton4Click(Sender: TObject);
    procedure RzButton2Click(Sender: TObject);
    procedure RzButton1Click(Sender: TObject);
    procedure RzButton3Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure RzButton5Click(Sender: TObject);
    procedure RzButton6Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure DetailBand1BeforePrint(Sender: TQRCustomBand;
      var PrintBand: Boolean);
    procedure DetailBand1AfterPrint(Sender: TQRCustomBand;
      BandPrinted: Boolean);
    procedure QuickRep1EndPage(Sender: TCustomQuickRep);
    procedure OpenPayment1Click(Sender: TObject);
    procedure RemovePayment1Click(Sender: TObject);
    procedure grdPaymentSummarySelectionChanged(Sender: TObject; ALeft,
      ATop, ARight, ABottom: Integer);
    procedure grdPaymentSummarySelectCell(Sender: TObject; ACol,
      ARow: Integer; var CanSelect: Boolean);
    procedure edtAmtPaidChange(Sender: TObject);
    procedure FlatButton1Click(Sender: TObject);
    procedure FlatButton2Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
    procedure grdPaymentSummaryGetAlignment(Sender: TObject; ARow,
      ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
    procedure btnCancelClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure cboLogBranchChange(Sender: TObject);
    procedure btnLoginClick(Sender: TObject);
    procedure Button6Click(Sender: TObject);
    procedure Button7Click(Sender: TObject);
    procedure RzButton4Click(Sender: TObject);
    procedure NewReviewee1Click(Sender: TObject);
    procedure TabSheet5Show(Sender: TObject);
    procedure btnFilterClick(Sender: TObject);
    procedure btnCreateEndHistClick(Sender: TObject);
    procedure btnCreateEndorsementClick(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure RzButton8Click(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure gridReviewerListCellClick(Column: TColumn);
    procedure Prepare1Click(Sender: TObject);
    procedure rzSpinPerFromChange(Sender: TObject);
    procedure rzTrackCRPerClick(Sender: TObject);
    procedure RzBitBtn2Click(Sender: TObject);
    procedure rzMainBtnExitClick(Sender: TObject);
    procedure rzMainBtnRegisterClick(Sender: TObject);
    procedure rzMainBtnSearchClick(Sender: TObject);
    procedure TabSheet2Click(Sender: TObject);
    procedure rzMainBtnPrintClick(Sender: TObject);
    procedure rzMainBtnLogoutClick(Sender: TObject);
    procedure rzMainBtnBillingClick(Sender: TObject);
    procedure TabSheet9Show(Sender: TObject);
    procedure rzbtneditSelectBillToButtonClick(Sender: TObject);
    procedure rzbtneditSelectBillToAltBtnClick(Sender: TObject);
    procedure rzcomboboxBillToDropdownSelect(Sender: TObject);
    procedure rzbitbtnBillToInfoButtonClick(Sender: TObject);
    procedure rzchkSelectAllParticularsClick(Sender: TObject);
    procedure rzMainBtnPassersClick(Sender: TObject);
    procedure rzMainBtnRebatesClick(Sender: TObject);
    procedure rzMainBtnAdminClick(Sender: TObject);
    procedure rzicbUserListSelect(Sender: TObject);
    procedure RzBitBtn4Click(Sender: TObject);
    procedure rzcPassersComlistSelect(Sender: TObject);
    procedure TabSheet10Show(Sender: TObject);
    procedure rzeditFullNameKeyPress(Sender: TObject; var Key: Char);
    procedure dsReviewerTableDataChange(Sender: TObject; Field: TField);
    procedure RzBitBtn5Click(Sender: TObject);
    procedure RzCheckBox2Click(Sender: TObject);
    procedure rzcbPassersForRebatesClick(Sender: TObject);
    procedure btnForRebatesPaymentClick(Sender: TObject);
    procedure TabSheet7Show(Sender: TObject);
    procedure RzBitBtn8Click(Sender: TObject);
    procedure RzBitBtn10Click(Sender: TObject);
    procedure RzBitBtn6Click(Sender: TObject);
    procedure btn_processRebatesClick(Sender: TObject);
    procedure gridRebatesForPaymentGetAlignment(Sender: TObject; ARow,
      ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
    procedure RzBitBtn9Click(Sender: TObject);

  private
    { Private declarations }
    strQuickAdd:string;
    BNewKey:Boolean;
    strAbbr:string;
    iPostData:boolean;
    iFlagClickBtn:boolean;
    iVarCounter:integer;
    procedure SetEndorsementGrid;
    procedure SetPassersGrid;    
    procedure IncShippingList2BillToDropdown(iFilter:integer;sFilter:String);
  public
    { Public declarations }
  intReportCode:integer;
  AConStr:string;
  fltRunBalance,fltRunPAmount,fltCurrBalance:Variant;
  intPK:integer;
  procedure ConvertToPDF;
  function ValidateEntry(AValue:string): string;      
  end;

var
  frmRegistrationMain: TfrmRegistrationMain;

implementation

{$R *.dfm}

procedure TfrmRegistrationMain.Button1Click(Sender: TObject);
var
  dtNow:TDate;
begin

    if  iPostData then
    begin
        rzToolbarRegEntry_btnPrint.Enabled:=False;
        rzToolbarRegEntry_btnPayments.Enabled:=False;
        rzToolbarRegEntry_btnNew.Enabled:=False;
        iPostData:=False;
        adoReviewerTable.Insert;
        adoReviewerTable.FieldByName('ENTEREDDATE').AsDateTime :=  Now();
        adoReviewerTable.FieldByName('DATEENROLL').AsDateTime :=  Now();
        adoReviewerTable.FieldByName('ENTEREDBY').AsString :=  Trim(cboLogUser.Text);
        adoReviewerTable.FieldByName('BRANCHNAME').AsString :=  Trim(cboLogBranch.Text);
        adoReviewerTable.FieldByName('REVSTATUS').AsString :=  'ONGOING';        
        //dtNow := EncodeDate(strtoint(FormatDateTime('yyyy',Now())),strtoint(FormatDateTime('mm',Now())),strtoint(FormatDateTime('dd',Now())));
        //dtDateEnroll.Date :=dtNow;
        edtFirstname.SetFocus;
        grdPaymentSummary.Clear;
        grdPaymentSummary.RowCount:=2;
        dtDateEnroll.DateTime := Now();
        frmRegistrationMain.Caption := 'Cebu Gems Registration System' + ' - [' +  Trim(cboLogBranch.Text) + '] - {NEW RECORD ADDED}';
        BNewKey:=True;
    end else
    begin
        if Application.MessageBox('Do you want to save this record?',
            'Save Record', MB_ICONINFORMATION + MB_YESNO) = IDYES then
            Button3Click(Sender)
        else
        begin
            adoReviewerTable.Cancel;
            iPostData:=True;
            Button1Click(Sender);
        end;
    end;
end;

procedure TfrmRegistrationMain.Button3Click(Sender: TObject);
function GetCurrentReviewerID(strBranch:string):integer;
begin
   BNewKey:=true;
   with TADOQuery.Create(nil) do
   try
     Connection := self.ADOConn;
     SQL.Text := 'SELECT * FROM REFERENCEID ' +
            ' WHERE MODULENAME =''REGISTRATION'' AND BRANCH = ''' + strBranch + '''';
     try
       Open;
     except
       Exit;
     end;

     if not IsEmpty then
     begin
        first;
        Result:=FieldByName('REFERENCEID').AsInteger;
     end;
   finally
     Free;
   end;
end;
function PostCurrentReviewerID(strBranch:string;intRefID:integer):Boolean;
begin
   BNewKey:=False;
   with TADOQuery.Create(nil) do
   try
     Connection := self.ADOConn;
     SQL.Text := 'SELECT * FROM REFERENCEID ' +
            ' WHERE MODULENAME =''REGISTRATION'' AND BRANCH = ''' + strBranch + '''';
     try
       Open;
     except
       Exit;
     end;

     if not IsEmpty then
     begin
        first;
        Edit;
        FieldByName('REFERENCEID').AsInteger:= intRefID+1;
        Post;
        result:=True;
     end;
   finally
     Free;
   end;
end;
var
iRevID:integer;
begin

    if (Trim(edtFirstname.Text)='') or (Trim(edtLastname.Text)='') then
    begin
      Application.MessageBox('Please enter Firstname/Lastname to complete your transaction.', 'Firstname/Lastname Required', MB_OK + MB_ICONERROR);
      edtFirstname.SetFocus;
      exit;
    end;

    if (Trim(RzDBNumericEdit1.Text)='0.00') or (Trim(RzDBNumericEdit1.Text)='') then
    begin
      Application.MessageBox('Please enter reviewer fee to complete your transaction.', 'Reviewer fee Required', MB_OK + MB_ICONERROR);
      RzDBNumericEdit1.SetFocus;
      exit;
    end;


    if BNewKey then
    begin
      adoReviewerTable.FieldByName('REVIEWERid').AsInteger := GetCurrentReviewerID(Trim(cboLogBranch.Text));
      rzToolbarRegEntry_btnPrint.Enabled:=PostCurrentReviewerID(Trim(cboLogBranch.Text),adoReviewerTable.FieldByName('REVIEWERid').AsInteger);
      rzToolbarRegEntry_btnNew.Enabled:= True;
      rzToolbarRegEntry_btnPayments.Enabled:= True;
    end
    ELSE begin
      adoReviewerTable.Edit;
    end;
    iRevID:= adoReviewerTable.FieldByName('REVIEWERid').AsInteger;
    adoReviewerTable.FieldByName('MODIFIEDDATE').AsDateTime :=  Now();
    adoReviewerTable.FieldByName('MODIFIEDBY').AsString :=  trim(cboLogUser.Text);
    if trim(adoReviewerTable.FieldByName('RFREMAINING').AsString) ='' then
        adoReviewerTable.FieldByName('RFREMAINING').AsVariant := adoReviewerTable.FieldByName('REVIEWERFEE').AsVariant;
    adoReviewerTable.Post;
    iPostData:=True;
    RzPageControl1.TabIndex:=1;
    adoReviewerList.Requery;
    adoReviewerList.Locate('REVIEWERid',iRevID,[]);

end;

procedure TfrmRegistrationMain.FormCreate(Sender: TObject);
var
sCGConn,sLocalConn,sCGConnOrmoc,sHostConn,sMDOConn,sEmallConn:string;
adoCheckTemp: TADODataSet;
strShowText:String;
iRowCounter:integer;
begin

  strShowText:= '';
  strQuickAdd := '';
  fltRunBalance :=0;
  intPK:=0;
  fltRunPAmount:=0;
 { sLocalConn := 'Provider=SQLOLEDB.1'
           + ';Password=mdoffice'
           + ';Persist Security Info=True'
           + ';User ID=sa'
           + ';Initial Catalog=HRIS'
           + ';Data Source=GERALD-PC\SQLEXPRESS2008';}

  sLocalConn := 'Provider=SQLOLEDB.1'
           + ';Password=mdoffice'
           + ';Persist Security Info=True'
           + ';User ID=sa'
           + ';Initial Catalog=CEBUGEMSHRIS'
           + ';Data Source=TOSHIBA\SQLEXPRESS';


  {sCGConn := 'Provider=SQLOLEDB.1'
          + ';Password=Gems2014'
          + ';Persist Security Info=True'
          + ';User ID=sa'
          + ';Initial Catalog=HRIS'
          + ';Data Source=tcp:192.168.0.111\SQLEXPRESS2008,49156';}
  sCGConn := 'Provider=SQLOLEDB.1'
          + ';Password=Gems@2014'
          + ';Persist Security Info=True'
          + ';User ID=sa'
          + ';Initial Catalog=CEBUGEMSHRIS'
          + ';Data Source=tcp:192.168.0.111\SQLEXPRESS,1433';


  sCGConnOrmoc := 'Provider=SQLOLEDB.1'
          + ';Password=Gems2014'
          + ';Persist Security Info=True'
          + ';User ID=sa'
          + ';Initial Catalog=HRIS'
          + ';Data Source=CEBUGEMS-PC\SQLEXPRESS2008';

 sHostConn := 'Provider=SQLOLEDB.1'
        + ';Password=Gems@2014'
        + ';Persist Security Info=True'
        + ';User ID=CEBUGEMSHRIS'
        + ';Initial Catalog=CEBUGEMSHRIS'
        + ';Data Source=CEBUGEMSHRIS.db.6779690.hostedresource.com';

 sMDOConn := 'Provider=SQLOLEDB.1'
        + ';Password=mdoffice'
        + ';Persist Security Info=True'
        + ';User ID=sa'
        + ';Initial Catalog=HRIS'
        + ';Data Source=KING-IKAB-PC\SQLEXPRESS2008';


 sEmallConn := 'Provider=SQLOLEDB.1'
        + ';Password=Gems@2014'
        + ';Persist Security Info=True'
        + ';User ID=sa'
        + ';Initial Catalog=CEBUGEMSHRIS'
        + ';Data Source=FRONTDESK-PC\SQLEXPRESS';



  AConStr := sHostConn;
  adoConn.Close;
  adoConn.ConnectionString:=AConStr;
  try
    adoConn.Connected:=True;
    adoConn.Open;
  except
    ShowMessage('Can''t connect to db.');
  end;


  adqTemp.Connection := adoConn;


  with adoReviewerTable do
  begin
    Close;
    Connection := ADOConn;
    CommandText := 'select * from REVIEWER where BRANCHNAME like ''%' + trim(cboLogBranch.Text) + '%''';
    Open;
  end;
  with adoBilling do
  begin
    Close;
    Connection := ADOConn;
    CommandText := 'select * from BILLING WHERE 1<>1';
    Open;
  end;

  with adoSchoolList do
  begin
    Close;
    Connection := ADOConn;
    CommandText := 'select SCHOOLKEY, upper(SCHOOLNAME) as SCHOOLNAME from SCHOOL order by SCHOOLNAME';
    Open;
  end;
  with adoRankList do
  begin
    Close;
    Connection := ADOConn;
    CommandText := 'select RANKKEY,upper(RANKNAME) as RANKNAME from RANK order by RANKNAME';
    Open;
  end;
  with adoShippingList do
  begin
    Close;
    Connection := ADOConn;
    CommandText := 'select SHIPPINGKEY,upper(SHIPPINGNAME) as SHIPPINGNAME from SHIPPING order by SHIPPINGNAME';
    Open;
  end;


  with adoEndorserList do
  begin
    Close;
    Connection := ADOConn;
    CommandText := 'select ENDORSERKEY,UPPER(ENDORSERFULL) as ENDORSERFULL from ENDORSER order by ENDORSERFULL';
    Open;
  end;

  strShowText:= 'select PM.PAYMENTARNO,convert(varchar,cast(PM.PAYMENTAMOUNT as money),-1) as PAYMENTAMOUNT,pm.PAYMENTDATE,rk.RANKNAME,rv.LASTNAME,rv.FIRSTNAME,rv.MIDDLENAME,' +
        ' convert(char(10),RV.DATEENROLL,101) as DATEENROLLED, (RV.LASTNAME + '', '' + RV.FIRSTNAME) as NAME,RV.BRANCHNAME' +
        ' from payment PM' +
        ' left join reviewer RV on rv.REVIEWERKEY=pm.REVIEWERKEY' +
        ' left join RANK RK on rk.RANKKEY=rv.RANKKEY' +
        ' order by RV.DATEENROLL DESC';
  //ShowMessage(strShowText);
  with adoReportsList do
  begin
    Close;
    Connection := ADOConn;
    CommandText := strShowText;
    Open;
  end;

  SetEndorsementGrid;
  pageSearchResults.ActivePageIndex := 0;

end;
procedure TfrmRegistrationMain.SetEndorsementGrid;
var
iRowCounter:integer;
begin

   with TADOQuery.Create(nil) do
   try
     Connection := self.ADOConn;
     SQL.Text := 'SELECT (UPPER(RV.LASTNAME) + '', '' + UPPER(RV.FIRSTNAME)) as NAME,EH.ENDORSEMENTHISTORYKEY,EH.ENDORSEMENTDATE' +
            ',EH.FROMBRANCH,EH.PREPAREDBY,EH.REMARKS,EH.REVIEWERKEY' +
            ' FROM ENDORSEMENTHISTORY EH' +
            ' LEFT JOIN REVIEWER RV ON RV.REVIEWERKEY=EH.REVIEWERKEY' +
            ' WHERE EH.ACCEPTEDBY IS NULL AND EH.TOBRANCH=''' + TRIM(cboLogBranch.Text) + '''';
     try
       Open;
     except
       Exit;
     end;

       With gridEndorsements do
       begin
         Clear;
         RowCount:=2;
         ColCount:=5;
         First;
         tabSheetEndorsement.Caption := 'Endorsements(' + inttostr(RecordCount)  +')'; 
         iRowCounter:=1;
         Cells[0,0] := 'From';
         Cells[1,0] := 'Date';
         Cells[2,0] := 'Enrolee';
         Cells[3,0] := 'Prepared By';
         Cells[4,0] := 'Remarks';
         ColWidths[0] := 90;
         ColWidths[1] := 90;
         ColWidths[2] := 150;
         ColWidths[3] := 150;
         ColWidths[4] := 300;

         if not IsEmpty then
         begin
           tabSheetEndorsement.Color := clRed;
           while not Eof do
           begin
             if iRowCounter >1 then AddRow;
             Cells[0,iRowCounter] := TRIM(FieldByName('FROMBRANCH').AsString);
             Cells[1,iRowCounter] := FormatDateTime('MM-DD-YYYY',FieldByName('ENDORSEMENTDATE').AsDateTime);
             Cells[2,iRowCounter] := TRIM(FieldByName('NAME').AsString);
             Cells[3,iRowCounter] := TRIM(FieldByName('PREPAREDBY').AsString);
             Cells[4,iRowCounter] := TRIM(FieldByName('REMARKS').AsString);
             Cells[5,iRowCounter] := TRIM(FieldByName('ENDORSEMENTHISTORYKEY').AsString);
             Cells[6,iRowCounter] := TRIM(FieldByName('REVIEWERKEY').AsString);             
             Next;
             iRowCounter:=iRowCounter+1;
           end;
         end;
       end;

     finally
       Free;
     end;

end;

procedure TfrmRegistrationMain.gridReviewerListDblClick(Sender: TObject);
var
strShowText:string;
iNdex,subiNdex:INTEGER;
begin
    strShowText := gridReviewerList.DataSource.DataSet.FieldByName('REVIEWERKEY').AsString;
    //ShowMessage(strShowText);
    adoReviewerTable.Locate('REVIEWERid',gridReviewerList.DataSource.DataSet.FieldByName('REVIEWERid').AsInteger,[]);
    adoReviewerTable.Edit;
    Button4.Enabled:=True;
    Button2.Enabled:=True;
    //RzPageControl1.TabIndexInView(RzPageControl1.TabIndex);
   with TADOQuery.Create(nil) do
   try
     Connection := self.ADOConn;
     SQL.Text := 'select PAYMENTARNO,PAYMENTDATE,PAYMENTAMOUNT,REMARKS,PAYMENTKEY,CHARGETO FROM PAYMENT ' +
            ' WHERE REVIEWERKEY = ' + gridReviewerList.DataSource.DataSet.FieldByName('REVIEWERKEY').AsString +
            ' ORDER BY PAYMENTKEY DESC';
     try
       Open;
     except
       Exit;
     end;
       grdPaymentSummary.Clear;
       grdPaymentSummary.RowCount:=2;
       grdPaymentSummary.ColCount:=6;
       First;
       iNdex:=1;
       grdPaymentSummary.Cells[0,0] := 'AR No.';
       grdPaymentSummary.Cells[1,0] := 'Date';
       grdPaymentSummary.Cells[2,0] := 'Amount';
       grdPaymentSummary.Cells[3,0] := 'Charge to';
       grdPaymentSummary.Cells[5,0] := 'Remarks';
       grdPaymentSummary.ColWidths[0] := 90;
       grdPaymentSummary.ColWidths[1] := 90;
       grdPaymentSummary.ColWidths[2] := 110;
       grdPaymentSummary.ColWidths[3] := 110;
       grdPaymentSummary.ColWidths[4] := 0;
       grdPaymentSummary.ColWidths[5] := 230;
       //grdPaymentSummary.CellProperties[0,0].Alignment := taCenter;
       //grdPaymentSummary.CellProperties[1,0].Alignment := taCenter;

     if not IsEmpty then
     begin
       while not Eof do
       begin
         if iNdex >1 then grdPaymentSummary.AddRow;
         grdPaymentSummary.Cells[0,iNdex] := TRIM(FieldByName('PAYMENTARNO').AsString);
         if trim(FieldByName('PAYMENTDATE').AsString) <> '' then
           grdPaymentSummary.Cells[1,iNdex] := FormatDateTime('MM-DD-YYYY',FieldByName('PAYMENTDATE').AsDateTime);
         if trim(FieldByName('PAYMENTAMOUNT').AsString) <>'' then
           grdPaymentSummary.Cells[2,iNdex] := FormatFloat('#,##0.00',FieldByName('PAYMENTAMOUNT').AsVariant);
         grdPaymentSummary.Cells[3,iNdex] := TRIM(FieldByName('CHARGETO').AsString);
         grdPaymentSummary.Cells[4,iNdex] := TRIM(FieldByName('PAYMENTKEY').AsString);
         grdPaymentSummary.Cells[5,iNdex] := TRIM(FieldByName('REMARKS').AsString);
         //grdPaymentSummary.CellProperties[0,iNdex].Alignment := taCenter;
         //grdPaymentSummary.CellProperties[1,iNdex].Alignment := taRightJustify;
         iNdex:=iNdex+1;
         Next;
       end;
     end;
   finally
     Free;
   end;

   with TADOQuery.Create(nil) do
   try
     Connection := self.ADOConn;
     SQL.Text := 'SELECT (UPPER(RV.LASTNAME) + '', '' + UPPER(RV.FIRSTNAME)) as NAME,EH.ENDORSEMENTHISTORYKEY,EH.ENDORSEMENTDATE' +
            ',EH.FROMBRANCH,EH.PREPAREDBY,EH.REMARKS,EH.REVIEWERKEY,EH.ACCEPTEDBY,EH.ACCEPTEDDATE,EH.TOBRANCH,EH.ORIGAMTBEFOREEND' +
            ',EH.AMTCRFROMBRANCH,EH.AMTCRTOBRANCH,EH.AMTPERFRBRANCH,EH.AMTPERTOBRANCH' +
            ' FROM ENDORSEMENTHISTORY EH' +
            ' LEFT JOIN REVIEWER RV ON RV.REVIEWERKEY=EH.REVIEWERKEY' +
            ' WHERE EH.REVIEWERKEY=' + gridReviewerList.DataSource.DataSet.FieldByName('REVIEWERKEY').AsString ;
     try
       Open;
     except
       Exit;
     end;

       With rzListView_Endorsements do
       begin
         Clear;
         iNdex:=0;
         subiNdex:=1;

         if not IsEmpty then
         begin
           First;
           while not Eof do
           begin
             rzListView_Endorsements.Items.Insert(iNdex).Caption := TRIM(FieldByName('FROMBRANCH').AsString);
             rzListView_Endorsements.Items.Item[iNdex].SubItems.Append(TRIM(FieldByName('TOBRANCH').AsString));
             rzListView_Endorsements.Items.Item[iNdex].SubItems.Append(TRIM(FieldByName('PREPAREDBY').AsString) + '[' + TRIM(FormatDateTime('MM-DD-YY',FieldByName('ENDORSEMENTDATE').AsDateTime)) + ']');
             if TRIM(FieldByName('ACCEPTEDBY').AsString)<>'' then
             begin
                rzListView_Endorsements.Items.Item[iNdex].SubItems.Append(TRIM(FieldByName('ACCEPTEDBY').AsString) + '[' + TRIM(FormatDateTime('MM-DD-YY',FieldByName('ACCEPTEDDATE').AsDateTime)) + ']');
                 rzListView_Endorsements.Items.Item[iNdex].SubItems.Append(TRIM(FormatFloat('#,##0.00',FieldByName('ORIGAMTBEFOREEND').AsVariant)));
                 rzListView_Endorsements.Items.Item[iNdex].SubItems.Append(TRIM(FormatFloat('#,##0.00',FieldByName('AMTCRFROMBRANCH').AsVariant)) + '/' + TRIM(FormatFloat('#,##0.00',FieldByName('AMTCRTOBRANCH').AsVariant)));
                 rzListView_Endorsements.Items.Item[iNdex].SubItems.Append(TRIM(FieldByName('AMTPERFRBRANCH').AsString) + '%/' + TRIM(FieldByName('AMTPERTOBRANCH').AsString) + '%');
             end else
                rzListView_Endorsements.Items.Item[iNdex].SubItems.Append(' -- pending status --');
             iNdex:=iNdex+1;
             Next;
           end;
         end;
       end;

     finally
       Free;
     end;

   RzPageControl1.ActivePageIndex := 0;
   frmRegistrationMain.Caption := frmRegistrationMain.Caption + ' - {VIEW/EDIT REC. NO.:' +  Trim(gridReviewerList.DataSource.DataSet.FieldByName('REVIEWERid').AsString) + '}';

end;

procedure TfrmRegistrationMain.dxButton1Click(Sender: TObject);
begin
    strQuickAdd := 'SCHOOL';
    pnlQuickAdd.Visible := True;
    pnlQuickAdd.Left := 215;
    edtName.SetFocus;
    RzGroupBox1.Caption := 'Quick Add - ( ' + strQuickAdd  + ' ):';
end;

procedure TfrmRegistrationMain.dxButton2Click(Sender: TObject);
begin
    strQuickAdd := 'RANK';
    pnlQuickAdd.Visible := True;
    pnlQuickAdd.Left := 215;
    edtName.SetFocus;
    RzGroupBox1.Caption := 'Quick Add - ( ' + strQuickAdd  + ' ):';
end;

procedure TfrmRegistrationMain.dxButton3Click(Sender: TObject);
begin
    strQuickAdd := 'SHIPPING';
    pnlQuickAdd.Visible := True;
    pnlQuickAdd.Left := 215;
    edtName.SetFocus;
    RzGroupBox1.Caption := 'Quick Add - ( ' + strQuickAdd  + ' ):';
end;

procedure TfrmRegistrationMain.dxButton4Click(Sender: TObject);
begin
    strQuickAdd := 'ENDORSER';
    pnlQuickAdd.Visible := True;
    pnlQuickAdd.Left := 215;    
    edtName.SetFocus;
    RzGroupBox1.Caption := 'Quick Add - ( ' + strQuickAdd  + ' ):';
end;

procedure TfrmRegistrationMain.RzButton2Click(Sender: TObject);
var
strSQLTemp:string;
begin

    strSQLTemp:='';
    if Trim(edtName.Text)='' then
    begin
      Application.MessageBox('Cannot accept blank text for this transaction.', 'QUICK ADD', MB_OK + MB_ICONERROR);
      edtName.SetFocus;
      exit;
    end;


   if Trim(edtName.Text)<> '' then
   begin
      if strQuickAdd = 'SCHOOL' then strSQLTemp := 'Select * from SCHOOL where SCHOOLNAME like ''%' + Trim(edtName.Text) + '%''';
      if strQuickAdd = 'ENDORSER' then strSQLTemp := 'Select * from ENDORSER where ENDORSERFULL like ''%' + Trim(edtName.Text) + '%''';
      if strQuickAdd = 'SHIPPING' then strSQLTemp := 'Select * from SHIPPING where SHIPPINGNAME like ''%' + Trim(edtName.Text) + '%''';
      if strQuickAdd = 'RANK' then strSQLTemp := 'Select * from RANK where RANKNAME like ''%' + Trim(edtName.Text) + '%''';
      
      with TADOQuery.Create(nil) do
      try
        Connection := self.ADOConn;
        SQL.Text := strSQLTemp;
        try
          Open;
        except
          Exit;
        end;
        if not IsEmpty then
        begin
            Application.MessageBox('Please check identical name in the database.', 'QUICK ADD', MB_OK + MB_ICONERROR);
            edtName.SetFocus;
            //Free;
            exit;
        end;
      finally
        Free;
      end;
   end;

    if trim(edtName.Text) <> '' then
    begin
        if strQuickAdd = 'SCHOOL' then
        begin
          with TADOCommand.Create(nil) do
          try
            Connection :=  self.ADOConn;
            CommandText := 'INSERT INTO SCHOOL (SCHOOLNAME,BRANCHENTERED,ENTEREDBY) VALUES (''' + trim(edtName.Text) + ''',''' + trim(cboLogBranch.Text) + ''',''' +  trim(cboLogUser.Text) + ''')';
            Execute;
          finally
            Free;
          end;
        end;

        if strQuickAdd = 'RANK' then
        begin
          with TADOCommand.Create(nil) do
          try
            Connection :=  self.ADOConn;
            CommandText := 'INSERT INTO RANK (RANKNAME,BRANCHENTERED,ENTEREDBY) VALUES (''' + trim(edtName.Text) + ''',''' + trim(cboLogBranch.Text) + ''',''' +  trim(cboLogUser.Text) + ''')';
            Execute;
          finally
            Free;
          end;
        end;

        if strQuickAdd = 'SHIPPING' then
        begin
          with TADOCommand.Create(nil) do
          try
            Connection :=  self.ADOConn;
            CommandText := 'INSERT INTO SHIPPING (SHIPPINGNAME,BRANCHENTERED,ENTEREDBY) VALUES (''' + trim(edtName.Text) + ''',''' + trim(cboLogBranch.Text) + ''',''' +  trim(cboLogUser.Text) + ''')';
            Execute;
          finally
            Free;
          end;
        end;

        if strQuickAdd = 'ENDORSER' then
        begin
          with TADOCommand.Create(nil) do
          try
            Connection :=  self.ADOConn;
            CommandText := 'INSERT INTO ENDORSER (ENDORSERFULL,BRANCHENTERED,ENTEREDBY) VALUES (''' + trim(edtName.Text) + ''',''' + trim(cboLogBranch.Text) + ''',''' +  trim(cboLogUser.Text) + ''')';
            Execute;
          finally
            Free;
          end;
        end;


    end;

    adoSchoolList.Requery;
    adoRankList.Requery;
    adoShippingList.Requery;
    adoEndorserList.Requery;
    if strQuickAdd = 'SCHOOL' then
        cbSchool.DropDown;
    if strQuickAdd = 'RANK' then
        cbRank.DropDown;
    if strQuickAdd = 'SHIPPING' then
        cbShipping.DropDown;
    if strQuickAdd = 'ENDORSER' then
        cbEndorser.DropDown;

    edtName.Text := '';
    pnlQuickAdd.Visible := False;


end;

procedure TfrmRegistrationMain.RzButton1Click(Sender: TObject);
begin
    edtName.SetFocus;
end;

procedure TfrmRegistrationMain.RzButton3Click(Sender: TObject);
begin
    pnlQuickAdd.Visible := False;
end;

procedure TfrmRegistrationMain.Button2Click(Sender: TObject);
var
fltTotalPayment:Variant;
begin
    fltTotalPayment:= 0;
    fltCurrBalance:=0;
    edtARNumber.Text:='';
    edtAmtPaid.Value:=0;
    edtDatePaid.Date:=Now();
    edtPaidRemarks.Text:='';
    edtPaymentKey.Text:='';    
    if Trim(RzDBNumericEdit1.Text)='' then
    begin
      Application.MessageBox('Please enter Reviewer Fee before payment transaction.', 'PAYMENT', MB_OK + MB_ICONERROR);
      RzDBNumericEdit1.SetFocus;
      exit;
    end;

      with TADOQuery.Create(nil) do
      try
        Connection := self.ADOConn;
        SQL.Text := 'select SUM(paymentamount) as TotalPayment from payment where REVIEWERKEY=' + adoReviewerTable.FieldByName('REVIEWERKEY').AsString;
        try
          Open;
        except
          Exit;
        end;
        if not IsEmpty then
        begin
            if trim(fieldByName('TotalPayment').AsString) <> '' then
                fltTotalPayment := fieldByName('TotalPayment').AsVariant
            else
                fltTotalPayment := 0;
        end;
      finally
        Free;
      end;

    if trim(adoReviewerTable.FieldByName('REVIEWERKEY').AsString) <> '' then
    begin
      pnlQuickPayment.Visible := True;
      pnlQuickPayment.Left := 215;
      RzGroupBox2.Caption := 'New Payment from - ( ' + gridReviewerList.DataSource.DataSet.FieldByName('NAME').AsString + ' ):';
      edtPaymentKey.Text := '';
      edtARNumber.SetFocus;
      edtCurrBalance.Value := RzDBNumericEdit1.Value-fltTotalPayment;
      fltCurrBalance:=edtCurrBalance.Value;
      edtAmtPaid.Value := edtCurrBalance.Value;
      edtAmtPaid.SelectAll;
      edtDatePaid.Date := Now();
    end;
end;

function TfrmRegistrationMain.ValidateEntry(AValue:string): string;
begin
  if length(AValue) > 0 then
    result := AValue
  else
    result :='0';
end;


procedure TfrmRegistrationMain.RzButton5Click(Sender: TObject);
var
strQuery:string;
iNdex:integer;
begin

    if (Trim(edtARNumber.Text)='') and (Trim(edtChargeTo.Text)='') then
    begin
      Application.MessageBox('Please enter AR Number to complete your payment transaction.', 'PAYMENT', MB_OK + MB_ICONERROR);
      edtARNumber.SetFocus;
      exit;
    end;

    if Trim(edtChargeTo.Text)='' then
    begin
        with TADOQuery.Create(nil) do
        try
          Connection := self.ADOConn;
          SQL.Text := 'Select * from PAYMENT where PAYMENTARNO like ''%' + Trim(edtARNumber.Text) + '%''';
          try
            Open;
          except
            Exit;
          end;
          if (not IsEmpty) and (trim(edtPaymentKey.Text)='') then
          begin
              Application.MessageBox('AR Number is already use in another transaction, Use another AR number to complete transaction.', 'DUPLICATE AR NUMBER', MB_OK + MB_ICONERROR);
              edtARNumber.SetFocus;
              exit;
          end;
        finally
          Free;
        end;
    end;


    if (Trim(edtAmtPaid.Text)='') or  (Trim(edtAmtPaid.Text)='0.00') then
    begin
      Application.MessageBox('Please enter Payment amount to complete your payment transaction.', 'PAYMENT', MB_OK + MB_ICONERROR);
      edtAmtPaid.SetFocus;
      exit;
    end;

    if edtAmtPaid.Value > fltCurrBalance then
    begin
      Application.MessageBox('Please pay only below your current balance.', 'PAYMENT', MB_OK + MB_ICONERROR);
      edtAmtPaid.SetFocus;
      exit;
    end;

   if Trim(edtPaymentKey.Text) = '' then
   begin

     with TADOCommand.Create(nil) do
     try
       Connection :=  self.ADOConn;
       //strQuery
       CommandText := 'INSERT INTO PAYMENT (REVIEWERKEY,PAYMENTAMOUNT,PAYMENTDATE,REMARKS,PAYMENTARNO,PAYMENTBAL,CHARGETO,ENTEREDBY,MODIFIEDBY) VALUES (' +
                gridReviewerList.DataSource.DataSet.FieldByName('REVIEWERKEY').AsString + ',' +
                StringReplace(ValidateEntry(edtAmtPaid.Text), ',','', [rfReplaceAll]) + ',''' +
                trim(edtDatePaid.Text) + ''',''' +
                TRIM(edtPaidRemarks.Text) + ''',''' +
                TRIM(edtARNumber.Text) + ''',''' +
                StringReplace(ValidateEntry(edtCurrBalance.Text), ',','', [rfReplaceAll]) + ''',''' +
                TRIM(edtChargeTo.Text) + ''',''' +
                TRIM(cboLogUser.Text) + ''',''' +
                TRIM(cboLogUser.Text) + ''')';
       Execute;

     finally
       Free;
     end;

   ShowMessage('Payment successfully added...');
   end
   else
   begin

     with TADOCommand.Create(nil) do
     try
       Connection :=  self.ADOConn;
       //strQuery
       CommandText := 'UPDATE PAYMENT SET PAYMENTAMOUNT=' + StringReplace(ValidateEntry(edtAmtPaid.Text), ',','', [rfReplaceAll]) +
                ',PAYMENTDATE=''' + edtDatePaid.Text + ''',REMARKS=''' + TRIM(edtPaidRemarks.Text) + ''',CHARGETO=''' + Trim(edtChargeTo.Text) +
                ''',DATEMODIFIED=''' + formatdatetime('yyyy-mm-dd',Now()) + ''',MODIFIEDBY=''' + TRIM(cboLogUser.Text) +
                ''',PAYMENTARNO=''' + TRIM(edtARNumber.Text) + ''',PAYMENTBAL=' + StringReplace(ValidateEntry(edtCurrBalance.Text), ',','', [rfReplaceAll]) +
                ' WHERE PAYMENTKEY=' + trim(edtPaymentKey.Text);
       Execute;

     finally
       Free;
     end;

   ShowMessage('Payment successfully update...');



   end;
   pnlQuickPayment.Visible := False;

   with TADOQuery.Create(nil) do
   try
     Connection := self.ADOConn;
     SQL.Text := 'select PAYMENTARNO,PAYMENTDATE,PAYMENTAMOUNT,REMARKS,PAYMENTKEY,CHARGETO FROM PAYMENT ' +
            ' WHERE REVIEWERKEY = ' + gridReviewerList.DataSource.DataSet.FieldByName('REVIEWERKEY').AsString +
            ' ORDER BY PAYMENTKEY DESC';
     try
       Open;
     except
       Exit;
     end;
     if not IsEmpty then
     begin
       grdPaymentSummary.Clear;
       grdPaymentSummary.RowCount:=2;
       First;
       iNdex:=1;
       grdPaymentSummary.Cells[0,0] := 'AR No.';
       grdPaymentSummary.Cells[1,0] := 'Date';
       grdPaymentSummary.Cells[2,0] := 'Amount';
       grdPaymentSummary.Cells[3,0] := 'Charge to';
       grdPaymentSummary.Cells[5,0] := 'Remarks';
       grdPaymentSummary.ColWidths[0] := 90;
       grdPaymentSummary.ColWidths[1] := 90;
       grdPaymentSummary.ColWidths[2] := 110;
       grdPaymentSummary.ColWidths[3] := 110;
       grdPaymentSummary.ColWidths[4] := 0;
       grdPaymentSummary.ColWidths[5] := 230;
       //grdPaymentSummary.CellProperties[0,0].Alignment := taCenter;
       //grdPaymentSummary.CellProperties[1,0].Alignment := taCenter;
       while not Eof do
       begin
         if iNdex > 1 then grdPaymentSummary.AddRow;
         grdPaymentSummary.Cells[0,iNdex] := TRIM(FieldByName('PAYMENTARNO').AsString);
         grdPaymentSummary.Cells[1,iNdex] := TRIM(FieldByName('PAYMENTDATE').AsString);
         grdPaymentSummary.Cells[2,iNdex] := FormatFloat('#,##0.00',FieldByName('PAYMENTAMOUNT').AsVariant);
         grdPaymentSummary.Cells[3,iNdex] := TRIM(FieldByName('CHARGETO').AsString);
         grdPaymentSummary.Cells[4,iNdex] := FieldByName('PAYMENTKEY').AsString;
         grdPaymentSummary.Cells[5,iNdex] := TRIM(FieldByName('REMARKS').AsString);
         //grdPaymentSummary.CellProperties[0,iNdex].Alignment := taCenter;
         //grdPaymentSummary.CellProperties[1,iNdex].Alignment := taRightJustify;
         Next;
         iNdex:=iNdex+1;
       end;
     end;
   finally
     Free;
   end;

end;

procedure TfrmRegistrationMain.RzButton6Click(Sender: TObject);
begin
    pnlQuickPayment.Visible := False;
end;

procedure TfrmRegistrationMain.Button4Click(Sender: TObject);
var
strCharge:string;
strInc:string;
begin
    intReportCode:=1;
    strCharge:='';
    strInc:='';
    //showmessage(trim(adoReviewerTable.FieldByName('REVIEWERid').AsString));
    if trim(adoReviewerTable.FieldByName('REVIEWERKEY').AsString) <> '' then
    begin
       with adoPaymentDetails do
       begin
          close;
          Connection  := Self.adoConn;
          CommandText := 'select PAYMENTARNO,PAYMENTDATE,convert(varchar,cast(PAYMENTAMOUNT as money),-1) as PAYMENTAMOUNT,' +
                ' convert(varchar,cast(PAYMENTBAL as money),-1) as PAYMENTBAL,CHARGETO FROM PAYMENT ' +
                ' WHERE REVIEWERKEY = ' + TRIM(adoReviewerTable.FieldByName('REVIEWERKEY').AsString);
          Open;

          if not IsEmpty then
          begin
            first;
            while not Eof do
            begin
              if TRIM(FieldByName('CHARGETO').AsString) <> '' then
              begin
                Last;
                strCharge:= '(' + uppercase(TRIM(FieldByName('CHARGETO').AsString)) + ' CHARGE)'
              END;
            next;
            end; 
          end;
       end;

       if Trim(adoReviewerTable.fieldbyname('GREENBOOK').AsString) = 'Y' then
                strInc:=strInc+'GREENBOOK, ';
       if Trim(adoReviewerTable.fieldbyname('PAMPHLET').AsString) = 'Y' then
                strInc:=strInc+'PAMPHLET, ';
       if Trim(adoReviewerTable.fieldbyname('COLREG').AsString) = 'Y' then
                strInc:=strInc+'COLREG, ';
       if Trim(adoReviewerTable.fieldbyname('FORMULA').AsString) = 'Y' then
                strInc:=strInc+'FORMULA, ';
       if Trim(adoReviewerTable.fieldbyname('ENGINEBOOK').AsString) = 'Y' then
                strInc:=strInc+'ENGINEBOOK, ';
       if Trim(adoReviewerTable.fieldbyname('NOTEBOOK').AsString) = 'Y' then
                strInc:=strInc+'NOTEBOOK, ';
       if Trim(adoReviewerTable.fieldbyname('BAG').AsString) = 'Y' then
                strInc:=strInc+'BAG, ';
       if Trim(adoReviewerTable.fieldbyname('POLOSHIRT1').AsString) = 'Y' then
                strInc:=strInc+'POLO SHIRT1, ';
       if Trim(adoReviewerTable.fieldbyname('POLOSHIRT2').AsString) = 'Y' then
                strInc:=strInc+'POLO SHIRT2, ';
       if Trim(adoReviewerTable.fieldbyname('IDCARD').AsString) = 'Y' then
                strInc:=strInc+'ID CARD, ';
       if Trim(adoReviewerTable.fieldbyname('IDSLING').AsString) = 'Y' then
                strInc:=strInc+'ID SLING, ';
       if Trim(adoReviewerTable.fieldbyname('TSHIRT1').AsString) = 'Y' then
                strInc:=strInc+'T-SHIRT1, ';
       if Trim(adoReviewerTable.fieldbyname('TSHIRT2').AsString) = 'Y' then
                strInc:=strInc+'T-SHIRT2, ';
       if Trim(adoReviewerTable.fieldbyname('TSHIRT1').AsString) = 'Y' then
                strInc:=strInc+'T-SHIRT3, ';


       fltRunBalance := adoReviewerTable.fieldbyname('REVIEWERFEE').AsVariant;
       lblReviewerID.Caption := 'REVIEWER ID: ' + strAbbr + '-' + RightStr(trim(adoReviewerTable.FieldByName('REVIEWERid').AsString),4);
       lblSatBranch.Caption := Trim(adoReviewerTable.fieldbyname('SATBRANCH').AsString);
       lblShipping.Caption :=  trim(cbShipping.Text);
       lblRemarks.Caption := trim(edtRemarks.Text);
       lblInclusions.Caption := trim(strInc);
       lblSchool.Caption := trim(cbSchool.Text);
       lblEndorsed.Caption := trim(cbEndorser.Text);
       lblChargeTo.Caption := trim(strCharge);
       lblPrinted.Caption := ' Printed in [' + trim(cboLogBranch.Text) + '] / ' + formatdatetime('yyyy-mm-dd hh:nn:ss',Now());
       lblEOff.Caption := 'Enrolling Officer : ' + trim(edtEnrollOfficer.Text);
       if trim(adoReviewerTable.fieldbyname('REVIEWERFEE').AsString) <> '' then
           lblFee.Caption := FormatFloat('#,##0.00', adoReviewerTable.fieldbyname('REVIEWERFEE').AsVariant);
       if trim(adoReviewerTable.fieldbyname('DATEENROLL').AsString) <> '' then
           lblDate.Caption := 'Date: ' + FormatDateTime('DD MMM YYYY', adoReviewerTable.fieldbyname('DATEENROLL').AsDateTime);
       QuickRep1.Prepare;
       ConvertToPDF;
    end;
end;

procedure TfrmRegistrationMain.ConvertToPDF;
var
  repPDF: TQRPDFDocumentFilter;
  sPDFFilePath,sPPChartSummaryPath:string;
  MySearch:TSearchRec;
begin
  Screen.Cursor:=crHourGlass;
  try

    if DirectoryExists(ExtractFilePath(Application.ExeName)+'Registration') then
     begin
       FindFirst(ExtractFilePath(Application.ExeName)+'Registration\' +'*.pdf',faAnyFile,MySearch);
       DeleteFile(ExtractFilePath(Application.ExeName)+'Registration\'+MySearch.Name);
       While FindNext(MySearch)=0 do
       begin
         DeleteFile(ExtractFilePath(Application.ExeName)+'Registration\'+MySearch.Name);
       end;
       FindClose(MySearch);
       RemoveDir(ExtractFilePath(Application.ExeName)+'Registration\');
     end;

    sPDFFilePath :=  ExtractFilePath(Application.ExeName) + 'Registration';
    if not DirectoryExists(sPDFFilePath) then  CreateDir(sPDFFilePath);

    sPPChartSummaryPath := sPDFFilePath + '\' + Trim(adoReviewerTable.fieldbyname('REVIEWERKEY').AsString) + FormatDateTime('mmddyynnss', Now) + '.pdf';

    repPDF := TQRPDFDocumentFilter.Create(sPPChartSummaryPath);

    try
      if intReportCode = 1 then
        QuickRep1.ExportToFilter(repPDF)
      else
        if intReportCode = 2 then
            QuickRep2.ExportToFilter(repPDF)
        else
            if intReportCode = 3 then
                QuickRep3.ExportToFilter(repPDF);
      gtPDFDocument1.LoadFromFile(sPPChartSummaryPath);
      gtPDFDocument1.SaveToFile(sPPChartSummaryPath,naEnable);

    finally
   //repPDF.Free;//Commented by Ranjan on 08 28 2012
   if IsValidObject(repPDF) then FreeAndNil(repPDF); //Ranjan 08 28 2012
    end;
  except
    on E:Exception do
      Application.MessageBox(PChar('Unable to convert to PDF. Error [' + E.Message + ']'), 'PDF Error');
  end;
  Screen.Cursor:=crDefault;
  Application.ProcessMessages;
  //Close;
end;


procedure TfrmRegistrationMain.DetailBand1BeforePrint(
  Sender: TQRCustomBand; var PrintBand: Boolean);
begin
    //fltRunPAmount := fltRunPAmount + adoPaymentDetails.fieldbyname('PAYMENTAMOUNT').AsVariant;
    //lblbalanceamount.Caption := FormatFloat('#,##0.00',fltRunBalance- fltRunPAmount);
end;

procedure TfrmRegistrationMain.DetailBand1AfterPrint(Sender: TQRCustomBand;
  BandPrinted: Boolean);
begin
    //fltRunBalance := fltRunBalance- fltRunPAmount;
    //fltRunPAmount:=0;
    //fltRunP/Amount:=0;
end;

procedure TfrmRegistrationMain.QuickRep1EndPage(Sender: TCustomQuickRep);
begin
   //fltRunPAmount:=0;
   //fltRunBalance:=0;
end;

procedure TfrmRegistrationMain.OpenPayment1Click(Sender: TObject);
var
fltTotalPayment:Variant;
begin
   //Showmessage('Open AR No. :' + grdPaymentSummary.Cells[4,grdPaymentSummary.Row]);
   fltTotalPayment:=0;
   with TADOQuery.Create(nil) do
   try
     Connection := self.ADOConn;
     SQL.Text := 'select SUM(paymentamount) as TotalPayment from payment where REVIEWERKEY=' + adoReviewerTable.FieldByName('REVIEWERKEY').AsString;
     try
       Open;
     except
       Exit;
     end;
     if not IsEmpty then
     begin
         if trim(fieldByName('TotalPayment').AsString) <> '' then
             fltTotalPayment := fieldByName('TotalPayment').AsVariant
         else
             fltTotalPayment := 0;
     end;
   finally
     Free;
   end;


   if trim(grdPaymentSummary.Cells[4,grdPaymentSummary.Row])<> '' then
   begin
      with TADOQuery.Create(nil) do
      try
        Connection := self.ADOConn;
        SQL.Text := 'select * FROM PAYMENT' +
               ' WHERE PAYMENTKEY = ' + grdPaymentSummary.Cells[4,grdPaymentSummary.Row];
        try
          Open;
        except
          Exit;
        end;
        if not IsEmpty then
        begin
          pnlQuickPayment.Visible := True;
          edtARNumber.SetFocus;
          edtARNumber.Text := TRIM(FieldByName('PAYMENTARNO').AsString);
          edtDatePaid.Date := FieldByName('PAYMENTDATE').AsDateTime;
          edtAmtPaid.Text  := FormatFloat('#,##0.00',FieldByName('PAYMENTAMOUNT').AsVariant);
          edtPaidRemarks.Text  := TRIM(FieldByName('REMARKS').AsString);
          edtChargeTo.Text := TRIM(FieldByName('CHARGETO').AsString);
          edtPaymentKey.Text := TRIM(FieldByName('PAYMENTKEY').AsString);
          edtCurrBalance.Value := RzDBNumericEdit1.Value - fltTotalPayment;
          fltCurrBalance:=edtCurrBalance.Value+FieldByName('PAYMENTAMOUNT').AsVariant;
        end;
      finally
        Free;
      end;
   end;


end;

procedure TfrmRegistrationMain.RemovePayment1Click(Sender: TObject);
var
iNdex:integer;
begin

    if trim(grdPaymentSummary.Cells[4,grdPaymentSummary.Row]) <> '' then
    begin
       if Application.MessageBox('Are you sure you want to delete this payment record?',
                                   'Delete Payment Record', MB_ICONINFORMATION + MB_YESNO) = IDYES then
       begin
         with TADOCommand.Create(nil) do
         try
           Connection :=  self.ADOConn;
           CommandText := 'delete FROM PAYMENT' +
                   ' WHERE PAYMENTKEY = ' + grdPaymentSummary.Cells[4,grdPaymentSummary.Row];
           Execute;
         finally
           Free;
         end;
       end;
       grdPaymentSummary.ClearRowSelect;

       with TADOQuery.Create(nil) do
       try
         Connection := self.ADOConn;
         SQL.Text := 'select PAYMENTARNO,PAYMENTDATE,PAYMENTAMOUNT,REMARKS,PAYMENTKEY FROM PAYMENT ' +
                ' WHERE REVIEWERKEY = ' + gridReviewerList.DataSource.DataSet.FieldByName('REVIEWERKEY').AsString +
                ' ORDER BY PAYMENTKEY DESC';
         try
           Open;
         except
           Exit;
         end;

           grdPaymentSummary.clear;
           grdPaymentSummary.RowCount:=2;
           First;
           iNdex:=1;
           grdPaymentSummary.Cells[0,0] := 'AR No.';
           grdPaymentSummary.Cells[1,0] := 'Date';
           grdPaymentSummary.Cells[2,0] := 'Amount';
           grdPaymentSummary.Cells[3,0] := 'Remarks';
           grdPaymentSummary.ColWidths[0] := 90;
           grdPaymentSummary.ColWidths[1] := 90;
           grdPaymentSummary.ColWidths[2] := 130;
           grdPaymentSummary.ColWidths[3] := 310;
           //grdPaymentSummary.CellProperties[0,0].Alignment := taCenter;
           //grdPaymentSummary.CellProperties[1,0].Alignment := taCenter;

         if not IsEmpty then
         begin
           while not Eof do
           begin
             if iNdex >1 then grdPaymentSummary.AddRow;
             grdPaymentSummary.Cells[0,iNdex] := FieldByName('PAYMENTARNO').AsString;
             grdPaymentSummary.Cells[1,iNdex] := FieldByName('PAYMENTDATE').AsString;
             grdPaymentSummary.Cells[2,iNdex] := FormatFloat('#,##0.00',FieldByName('PAYMENTAMOUNT').AsVariant);
             grdPaymentSummary.Cells[3,iNdex] := FieldByName('REMARKS').AsString;
             grdPaymentSummary.Cells[4,iNdex] := FieldByName('PAYMENTKEY').AsString;
             //grdPaymentSummary.CellProperties[0,iNdex].Alignment := taCenter;
             //grdPaymentSummary.CellProperties[1,iNdex].Alignment := taRightJustify;
             Next;
             iNdex:=iNdex+1;
           end;
         end;
       finally
         Free;
       end;

    end;

end;

procedure TfrmRegistrationMain.grdPaymentSummarySelectionChanged(
  Sender: TObject; ALeft, ATop, ARight, ABottom: Integer);
begin
    OpenPayment1.Enabled :=trim(grdPaymentSummary.Cells[4,grdPaymentSummary.Row])<> '';
    RemovePayment1.Enabled :=trim(grdPaymentSummary.Cells[4,grdPaymentSummary.Row])<> '';
end;

procedure TfrmRegistrationMain.grdPaymentSummarySelectCell(Sender: TObject;
  ACol, ARow: Integer; var CanSelect: Boolean);
begin
    OpenPayment1.Enabled :=trim(grdPaymentSummary.Cells[4,grdPaymentSummary.Row])<> '';
    RemovePayment1.Enabled :=trim(grdPaymentSummary.Cells[4,grdPaymentSummary.Row])<> '';
end;

procedure TfrmRegistrationMain.edtAmtPaidChange(Sender: TObject);
begin
    edtCurrBalance.Value:= fltCurrBalance - edtAmtPaid.Value;
end;

procedure TfrmRegistrationMain.FlatButton1Click(Sender: TObject);
var
strSQL,strFilter:string;
begin
  strSQL := '';
  strFilter:= '';

  strSQL:= 'select RV.REVSTATUS, PM.PAYMENTARNO,convert(varchar,cast(PM.PAYMENTAMOUNT as money),-1) as PAYMENTAMOUNT,pm.PAYMENTDATE,rk.RANKNAME,upper(rv.LASTNAME) as LASTNAME,upper(rv.FIRSTNAME) as FIRSTNAME,upper(rv.MIDDLENAME) as MIDDLENAME,' +
        ' convert(char(10),RV.DATEENROLL,101) as DATEENROLLED, (RV.LASTNAME + '', '' + RV.FIRSTNAME) as NAME,RV.BRANCHNAME,ED.ENDORSERFULL,rv.ENTEREDBY,RV.REVIEWERID' +
        ' from payment PM' +
        ' left join reviewer RV on rv.REVIEWERKEY=pm.REVIEWERKEY' +
        ' left join RANK RK on rk.RANKKEY=rv.RANKKEY' +
        ' left join SHIPPING SHP on SHP.SHIPPINGKEY=RV.SHIPPINGKEY' +
        ' left join SCHOOL SCL on SCL.SCHOOLKEY=RV.SCHOOLKEY' +
        ' left join ENDORSER ED on ED.ENDORSERKEY=RV.ENDORSERKEY' + 
        ' where pm.PAYMENTDATE between ''' + FormatDateTime('yyyy-mm-dd',edtFilterDateFrom.DateTime) + '''' +
        ' and ''' + FormatDateTime('yyyy-mm-dd',edtFilterDateTo.DateTime) + '''';

   if trim(cboFilterBranch.Text)<>'' then
      strSQL:= strSQL + ' and (RV.BRANCHNAME LIKE ''%' + trim(cboFilterBranch.Text) + '%'')';

   if trim(edtFilterReviewer.Text)<>'' then
      strSQL:= strSQL + ' and (RV.LASTNAME + '', '' + RV.FIRSTNAME) LIKE ''%' + trim(edtFilterReviewer.Text) + '%''';

   if (trim(edtFilterARFrom.Text)<> '') and (trim(edtFilterARTo.Text)<> '')  then
      strSQL:= strSQL + ' and (PM.PAYMENTARNO >=' + trim(edtFilterARFrom.Text) + ' and PM.PAYMENTARNO <=' + trim(edtFilterARFrom.Text) + ')';

   if trim(cboFilterStatus.Text)<>'' then
      strSQL:= strSQL + ' and (RV.REVSTATUS = ''' + trim(cboFilterStatus.Text) + ''')';

  if trim(cboFilterCompany.Text) <> '' then
      strSQL:= strSQL +  ' and (SHP.SHIPPINGNAME like ''%' + trim(cboFilterCompany.Text) + '%'')';

  if trim(edtFilterReportSchool.Text) <> '' then
    strSQL:= strSQL + ' and (SCL.SCHOOLNAME like ''%' + trim(edtFilterReportSchool.Text) + '%'')';

  if trim(cboFilterEndorser.Text) <> '' then
    strSQL:= strSQL + ' and (ed.ENDORSERFULL like ''%' + trim(cboFilterEndorser.Text) + '%'')';



   strSQL:= strSQL + ' Order by pm.PAYMENTDATE';
  //showmessage(strSQL);
  with adoReportsList do
  begin
    Close;
    Connection := ADOConn;
    CommandText := strSQL;
    Open;
  end;
  if adoReportsList.RecordCount >1 then
    rzFilterStatusbar.Caption:= 'Filter results: ' +  IntToStr(adoReportsList.RecordCount) + ' rows'
  else
    rzFilterStatusbar.Caption:= 'Filter results: ' +  IntToStr(adoReportsList.RecordCount) + ' row';
  grdReports.Refresh;
end;

procedure TfrmRegistrationMain.FlatButton2Click(Sender: TObject);
begin
  {
    FlatButton1Click(Sender);
    if adoReportsList.RecordCount<1 then
    begin
     Application.MessageBox('Please check filter options, No records to show.', 'No Records', MB_ICONEXCLAMATION);
     Exit;
    end;

   intReportCode:=2;
   if DaysBetween(edtFilterDateFrom.DateTime,edtFilterDateTo.DateTime)>1 then
   begin
      QRLHeader.Caption := 'COLLECTION REPORT [' + UpperCase(TRIM(cboLogBranch.Text)) + ']';
      QRLFilter.Caption := 'Collection Date Range: ' + FormatDateTime('MMM-DD-YYYY', edtFilterDateFrom.DateTime) + ' - ' + FormatDateTime('MMM-DD-YYYY', edtFilterDateTo.DateTime);
   end
   else
   begin
      QRLHeader.Caption := 'DAILY COLLECTION REPORT [' + UpperCase(TRIM(cboLogBranch.Text)) + ']';
      QRLFilter.Caption := 'Collection Date: ' + FormatDateTime('MMM-DD-YYYY', edtFilterDateFrom.DateTime);
   end;
   QRLReportingDate.Caption :='Reporting Date: ' + FormatDateTime('MMM-DD-YYYY', Now());
   QuickRep2.Prepare;
   ConvertToPDF;}
   QuickRep5.Preview;
end;

procedure TfrmRegistrationMain.Button5Click(Sender: TObject);
var
sLast,sFirst:string;
iUpdateKey:integer;
begin

         sLast := '';
         sFirst:= '';
         iUpdateKey:=0;
         with TADOQuery.Create(nil) do
         try
           Connection := self.ADOConn;
           SQL.Text := 'select * from reviewer order by 1';
           Open;

            if not IsEmpty then
            begin
              first;
              while not Eof do
              begin
               sLast:= fieldbyname('FIRSTNAME').AsString;
               sFirst:= fieldbyname('LASTNAME').AsString;
               iUpdateKey:=fieldbyname('REVIEWERKEY').AsInteger;
               with TADOCommand.Create(nil) do
               try
                 Connection :=  self.ADOConn;
                 CommandText := 'UPDATE REVIEWER SET LASTNAME=''' + sLast + ''', FIRSTNAME=''' + sFirst + ''' WHERE REVIEWERKEY=' + inttostr(iUpdateKey);
                 Execute;
               finally
                 Free;
               end;
                Next;
              end;
            end;
       finally
         Free;
       end;




end;

procedure TfrmRegistrationMain.grdPaymentSummaryGetAlignment(
  Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment;
  var VAlign: TVAlignment);
begin
  if (ACol = 2)  then HAlign := taRightJustify;
  //if ACol = 1 then HAlign := taCenter;
end;

procedure TfrmRegistrationMain.btnCancelClick(Sender: TObject);
begin
  close;
end;

procedure TfrmRegistrationMain.FormShow(Sender: TObject);
  procedure InitBranch;
  begin
    with adqTemp do begin
      Close;
      CommandTimeout := 6000;
      SQL.Text := 'select distinct BRANCHNAME from EMPLOYEE where len(BRANCHNAME) > 1' +
          ' order by BRANCHNAME';
      Open;
      if not IsEmpty then
      begin
        cboLogBranch.ClearItems;
        First;
        while not Eof do begin
          cboLogBranch.Items.Add(UpperCase(FieldByName('BRANCHNAME').AsString));
          Next;
        end;
      end;
    end;

  end;

  procedure InitStaff(sBranch:string;strSup:string);
  var
    AStaffObj: TStaffObj;
    nIndex: Integer;
    strSQLSource:string;
  begin
    with adqTemp do begin
      Close;
      CommandTimeout := 6000;
      strSQLSource :='select EMPLOYEECODE,DTRLINKNAME,BRANCHNAME,DEPARTMENT,USERNAME from EMPLOYEE where ACCESSREGSYS=''Y'' and BRANCHNAME = ''' + trim(sBranch) + '''';

      if strSup='N' then
          strSQLSource:= strSQLSource + ' and left(department,4)<>''FINA'' and department<>'''''
      else
          strSQLSource:= strSQLSource + ' and (left(department,4)=''FINA'' or department='''')';

      SQL.Text := strSQLSource+
          ' order by DTRLINKNAME';
      Open;
      if not IsEmpty then
      begin
        cboLogUser.ClearItems;

        AStaffObj := TStaffObj.Create;
        AStaffObj.StaffKey := 0;
        AStaffObj.Name := '';
        AStaffObj.Branch := '';
        AStaffObj.Department := '';
        cboLogUser.Items.AddObject('', AStaffObj);
        nIndex:=0;
        First;
        while not Eof do begin
          AStaffObj := TStaffObj.Create;
          AStaffObj.StaffKey := FieldByName('EMPLOYEECODE').AsInteger;
          if (leftstr(trim(FieldByName('DEPARTMENT').AsString),4) = 'FINA') OR (trim(FieldByName('DEPARTMENT').AsString)='') then
            AStaffObj.Name := '(A) - ' + UpperCase(trim(FieldByName('DTRLINKNAME').AsString))
          else
            AStaffObj.Name := UpperCase(FieldByName('DTRLINKNAME').AsString);
          AStaffObj.Branch := UpperCase(FieldByName('BRANCHNAME').AsString);
          AStaffObj.Department := UpperCase(FieldByName('DEPARTMENT').AsString);
          cboLogUser.Items.AddObject(AStaffObj.Name, AStaffObj);
          rzicbUserList.AddItem(AStaffObj.Name,40,0);
          //rzicbUserList.InsertObject(AStaffObj.StaffKey,AStaffObj.Name,AStaffObj);
          //rzicbUserList.Items.AddObject(AStaffObj.Name, AStaffObj);
          //nIndex:=rzicbUserList.Add(AStaffObj.Name);
          //rzicbUserList.ImageComboItem[nIndex].Tag:= AStaffObj.StaffKey;
          //nIndex:=nIndex+1;
          Next;
        end;
      end;
    end;
  end;

var
  strPath:String;
  fConfig:TIniFile;
begin
  try
    strPath := ExtractFilePath(Application.Exename);
    fConfig := TInifile.Create(strPath + '\CG.ini');
    cboLogBranch.Text := fConfig.ReadString('Main', 'BRANCHNAME', '');
    edtFilterDateEnd.DateTime:= Now();
    edtFilterDateTo.DateTime := Now();
    pnlEndorsetoBranch.Left:=131;
    pnlQuickAdd.Left:=215;
    pnlQuickPayment.Left:=215;
    iFlagClickBtn:=False;
    

    if cboLogBranch.Text = '' then
    begin
      Application.MessageBox('Please initialize branchname.', 'No Password');
      Close;
      Exit;
    end;

    if trim(cboLogBranch.Text) <> '' then
      InitStaff(trim(cboLogBranch.Text),fConfig.ReadString('Main', 'SUP', ''));

    strAbbr:='';
    iPostData:=True;
    RzPageControl1.ActivePageIndex:=4;
    cboLogUser.SetFocus;

    FreeAndNil(fCOnfig);
  except
    on E: Exception do
      ForceWriteToApplicationLog('Error in TfLogon.SwitchConnection2 .. error details : ' + E.Message); // Sarma  Oct.25.2012
  end;


end;

procedure TfrmRegistrationMain.cboLogBranchChange(Sender: TObject);
  procedure InitStaff(sBranch:string);
  var
    AStaffObj: TStaffObj;
    nIndex: Integer;
  begin
    with adqTemp do begin
      Close;
      CommandTimeout := 6000; //sarma on jan.23.2013
      SQL.Text := 'select EMPLOYEECODE,DTRLINKNAME,BRANCHNAME,DEPARTMENT,USERNAME from EMPLOYEE where ACCESSREGSYS=''Y'' and BRANCHNAME = ''' + trim(sBranch) + '''' +
          ' order by DTRLINKNAME';
      Open;
      if not IsEmpty then
      begin
        cboLogUser.ClearItems;

        AStaffObj := TStaffObj.Create;
        AStaffObj.StaffKey := 0;
        AStaffObj.Name := '';
        AStaffObj.Branch := '';
        AStaffObj.Department := '';
        cboLogUser.Items.AddObject('', AStaffObj);

        First;
        while not Eof do begin
          AStaffObj := TStaffObj.Create;
          AStaffObj.StaffKey := FieldByName('EMPLOYEECODE').AsInteger;
          if leftstr(trim(FieldByName('USERNAME').AsString),4) = 'acct' then
            AStaffObj.Name := 'Accounting -' + UpperCase(trim(FieldByName('DTRLINKNAME').AsString))
          else
            AStaffObj.Name := UpperCase(FieldByName('DTRLINKNAME').AsString);
          AStaffObj.Branch := UpperCase(FieldByName('BRANCHNAME').AsString);
          AStaffObj.Department := UpperCase(FieldByName('DEPARTMENT').AsString);
          cboLogUser.Items.AddObject(AStaffObj.Name, AStaffObj);
          Next;
        end;
      end;
    end;
  end;
begin
 // if trim(cboLogBranch.Text) <> '' then
 //   InitStaff(trim(cboLogBranch.Text));

end;

procedure TfrmRegistrationMain.btnLoginClick(Sender: TObject);
function GetComputerNameFromWindows: string;
var
  iLen: Cardinal;
begin
  iLen := MAX_COMPUTERNAME_LENGTH + 1;         // From Windows.pas
  Result := StringOfChar(#0, iLen);
  GetComputerName(PChar(Result), iLen);
  SetLength(Result, iLen);
end;
Function GetIPAddress():String;
type
  pu_long = ^u_long;
var
  varTWSAData : TWSAData;
  varPHostEnt : PHostEnt;
  varTInAddr : TInAddr;
  namebuf : Array[0..255] of char;
begin
  If WSAStartup($101,varTWSAData) <> 0 Then
  Result := 'No. IP Address'
  Else Begin
    gethostname(namebuf,sizeof(namebuf));
    varPHostEnt := gethostbyname(namebuf);
    varTInAddr.S_addr := u_long(pu_long(varPHostEnt^.h_addr_list^)^);
    Result := 'IP Address: '+inet_ntoa(varTInAddr);
  End;
  WSACleanup;
end;
function GetVersionNumber: String;
const
  InfoNum = 10;
  InfoStr: array[1..InfoNum] of string = ('CompanyName', 'FileDescription', 'FileVersion', 'InternalName', 'LegalCopyright', 'LegalTradeMarks', 'OriginalFileName', 'ProductName', 'ProductVersion', 'Comments');
var
  S: string;
  n, Len: DWORD;
  Buf: PChar;
  Value: PChar;
begin
  S := Application.ExeName;
  n := GetFileVersionInfoSize(PChar(S), n);
  if n > 0 then
  begin
    Buf := AllocMem(n);
    GetFileVersionInfo(PChar(S), 0, n, Buf);
      if VerQueryValue(Buf, PChar('StringFileInfo\040904E4\' + InfoStr[3]), Pointer(Value), Len) then
        Result := Value;
    FreeMem(Buf, n);
  end;
end;

procedure InsertLogToHistory(sLogUser:string;sLogPass:string);
var
   adoLogInsert: TADOQuery;
begin
      try

       adoLogInsert := TADOQuery.Create(nil);
       adoLogInsert.Connection:= adoConn;
       adoLogInsert.Close;
       adoLogInsert.SQL.Clear;
       adoLogInsert.SQL.Text := 'INSERT INTO LOGINHISTORY(LOGINUSER,LOGINPASS,LOGINDATE,LOGINCOMNAME,LOGINIP,APPVERSION) VALUES (''' + TRIM(sLogUser) + ''',''' + TRIM(sLogPass) + ''',''' + FormatDateTime('YYYY-MM-DD HH:NN:SS',Now()) + ''',''' +
          GetComputerNameFromWindows + ''',''' +  GetIPAddress + ''',''WinRegVer ' + GetVersionNumber + ''')';
       adoLogInsert.ExecSQL ;

       adoLogInsert.Close;
       adoLogInsert.SQL.Clear;
       adoLogInsert.SQL.Text := 'select * from LOGINHISTORY where LOGINUSER =''' + TRIM(sLogUser) + ''' order by 1 desc';
       adoLogInsert.Open;

       if not  adoLogInsert.IsEmpty then
       begin
         adoLogInsert.First;
         if adoLogInsert.RecordCount=1 then
         begin
            //sLastLogin:= ' Last Login: ' + adoLogInsert.fieldByName('LOGINDATE').AsString;
         end else
         begin
            adoLogInsert.Next;
            //sLastLogin:= ' Last Login: ' + adoLogInsert.fieldByName('LOGINDATE').AsString;
         end;
       end;

       if IsValidObject(adoLogInsert) then FreeAndNil(adoLogInsert);
       except
       on E : Exception do
         ForceWriteToApplicationLog('Error in ' + 'INSERT INTO LOGINHISTORY(LOGINUSER,LOGINPASS,LOGINDATE,LOGINCOMNAME,LOGINIP,APPVERSION) VALUES (''' + TRIM(sLogUser) + ''',''' + TRIM(sLogPass) + ''',''' + FormatDateTime('YYYY-MM-DD',Now()) + ''',''' +
          GetComputerNameFromWindows + ''',''' +  GetIPAddress + ''',''' + GetVersionNumber + ''')' + E.Message);
       end;
end;
var
  strSQLRevList:string;
begin

  if Trim(cboLogBranch.Text) = '' then
  begin
   Application.MessageBox('Please select a branch.', 'Branch Required', MB_ICONEXCLAMATION);
   cboLogBranch.SetFocus;
   Exit;
  end;

  if Trim(cboLogUser.Text) = '' then
  begin
   Application.MessageBox('Please select a username.', 'Username Required', MB_ICONEXCLAMATION);
   cboLogUser.SetFocus;
   Exit;
  end;


  strSQLRevList:= 'select RV.REVIEWERKEY, convert(char(10),RV.DATEENROLL,101) as DATEENROLLED, RNK.RANKNAME, (UPPER(RV.LASTNAME) + '', '' + UPPER(RV.FIRSTNAME)) as NAME,RV.REVIEWERid, REF.ABBR,' +
        ' UPPER(SHP.SHIPPINGNAME) as SHIPPINGNAME, UPPER(SCL.SCHOOLNAME) as SCHOOLNAME,UPPER(RV.REVSTATUS) as REVSTATUS' +
        ' from REVIEWER RV' +
        ' left join RANK RNK on RNK.RANKKEY=RV.RANKKEY' +
        ' left join SHIPPING SHP on SHP.SHIPPINGKEY=RV.SHIPPINGKEY' +
        ' left join SCHOOL SCL on SCL.SCHOOLKEY=RV.SCHOOLKEY' +
        ' left join REFERENCEID REF ON REF.BRANCH=RV.BRANCHNAME AND REF.MODULENAME=''REGISTRATION'''+
        ' where RV.reviewerid IS NOT NULL AND RV.BRANCHNAME = ''' + Trim(cboLogBranch.Text) + '''' +
        ' order by RV.DATEENROLL DESC';

  if cboLogUser.Text = 'Admin' then
    strSQLRevList:='select RV.REVIEWERKEY, convert(char(10),RV.DATEENROLL,101) as DATEENROLLED, RNK.RANKNAME, (UPPER(RV.LASTNAME) + '', '' + UPPER(RV.FIRSTNAME)) as NAME,RV.REVIEWERid, REF.ABBR,' +
        ' UPPER(SHP.SHIPPINGNAME) as SHIPPINGNAME, UPPER(SCL.SCHOOLNAME) as SCHOOLNAME,UPPER(RV.REVSTATUS) as REVSTATUS' +
        ' from REVIEWER RV' +
        ' left join RANK RNK on RNK.RANKKEY=RV.RANKKEY' +
        ' left join SHIPPING SHP on SHP.SHIPPINGKEY=RV.SHIPPINGKEY' +
        ' left join SCHOOL SCL on SCL.SCHOOLKEY=RV.SCHOOLKEY' +
        ' left join REFERENCEID REF ON REF.BRANCH=RV.BRANCHNAME AND REF.MODULENAME=''REGISTRATION'''+
        ' where RV.reviewerid IS NOT NULL' +
        ' order by RV.DATEENROLL DESC';

  with adoReviewerList do
  begin
    Close;
    Connection := ADOConn;
    CommandText := strSQLRevList;
    Open;
  end;

  if leftstr(trim(cboLogUser.Text),3) ='(A)' then
      RzPageControl1.ActivePageIndex:=3
  else
  begin
      RzPageControl1.ActivePageIndex:=1;
      edtEnrollOfficer.Text := cboLogUser.Text;
  end;

  with adoSatBranchList do
  begin
    Close;
    Connection := ADOConn;
    CommandText := 'select SATBRANCHKEY,upper(SATBRANCH) as SATBRANCH from SATBRANCH where branch=''' + Trim(cboLogBranch.Text) + ''' order by SATBRANCH';
    Open;
  end;

  if TRIM(adoReviewerList.FIEldbyname('ABBR').AsString) <> '' then
    strAbbr:= TRIM(adoReviewerList.FIEldbyname('ABBR').AsString);
  frmRegistrationMain.Caption := frmRegistrationMain.Caption + ' - [' +  Trim(cboLogBranch.Text) + ']';
  InsertLogToHistory(Trim(cboLogUser.Text),Trim(cboLogBranch.Text));
  main_rzPanelMainMenu.Visible:=True;
  main_rzStatusBarMain.Visible:=True;
end;

procedure TfrmRegistrationMain.Button6Click(Sender: TObject);
begin
  RzPageControl1.ActivePageIndex:=1;
  edtEnrollOfficer.Text := cboLogUser.Text;
  frmRegistrationMain.Caption := 'Cebu Gems Registration System - [' +  Trim(cboLogBranch.Text) + ']';

end;

procedure TfrmRegistrationMain.Button7Click(Sender: TObject);
      procedure SyncReviewerToMain(strMessage: WideString);
      var
        strLog: widestring;
        eLog: TextFile;
        strPath: string;
        sLogFileName: string;
        sELogFileName,sStaffKey : String; 
      begin
        try
          if Pos('abort', LowerCase(strMessage)) > 0 then 
            Exit;

          strPath := ExtractFilePath(Application.Exename);

          sELogFileName := 'SyncData_'+  Trim(cboLogBranch.Text) + '_' + FormatDateTime('mmddyyyyhhnnss', Now)+'.log';

          strPath := strPath+'SyncLog\';

          if not DirectoryExists(strPath) then
            ForceDirectories(strPath);

          strLog := Format('%s%s',
            ['', strMessage]);

          AssignFile(eLog, strPath + sELogFileName );

          if FileExists(strPath + sELogFileName) then
            Append(eLog)
          else
            ReWrite(eLog);

          Writeln(eLog, strLog);
          CloseFile(eLog);
        except
          //
        end;
      end;
var
  strRecord:string;
begin
    with adqTemp do begin
      Close;
      CommandTimeout := 6000; //sarma on jan.23.2013
      SQL.Text := 'select * from REVIEWER where syncadmin<>''Y'' order by 1';
      Open;
      if not IsEmpty then
      begin
        First;
        RzProgressStatus1.TotalParts:= RecordCount;
        while not Eof do begin
          strRecord:='';
          RzProgressStatus1.IncPartsByOne;
          Edit;
          FieldByName('SYNCADMIN').AsString := 'Y';
          FieldByName('SYNCDATE').AsDateTime := Now();
          Post;
          strRecord:= Trim(FieldByName('REVIEWERKEY').AsString) + '; ' +
              Trim(FieldByName('RANKKEY').AsString) + '; ' +
              Trim(FieldByName('DATEENROLL').AsString) + '; ' +
              Trim(FieldByName('LASTNAME').AsString) + '; ' +
              Trim(FieldByName('FIRSTNAME').AsString) + '; ' +
              Trim(FieldByName('MIDDLENAME').AsString) + '; ' +
              Trim(FieldByName('EMAIL').AsString) + '; ' +
              Trim(FieldByName('MOBILE').AsString) + '; ' +
              Trim(FieldByName('PHONE').AsString) + '; ' +
              Trim(FieldByName('ADDRESS').AsString) + '; ' +
              Trim(FieldByName('SCHOOLKEY').AsString) + '; ' +
              Trim(FieldByName('SHIPPINGKEY').AsString) + '; ' +
              Trim(FieldByName('ENDORSERKEY').AsString) + '; ' +
              Trim(FieldByName('CONTACT').AsString) + '; ' +
              Trim(FieldByName('CONTACTNO').AsString) + '; ' +
              Trim(FieldByName('REMARKS').AsString)+ '; ' +
              Trim(FieldByName('REVIEWERFEE').AsString)+ '; ' +
              Trim(FieldByName('REVIEWERPASS').AsString)+ '; ' +
              Trim(FieldByName('ACCESSEXPIRATIONDATE').AsString)+ '; ' +
              Trim(FieldByName('BRANCHNAME').AsString)+ '; ' +
              Trim(FieldByName('ENTEREDBY').AsString)+ '; ' +
              Trim(FieldByName('ENTEREDDATE').AsString)+ '; ' +
              Trim(FieldByName('MODIFIEDBY').AsString)+ '; ' +
              Trim(FieldByName('MODIFIEDDATE').AsString)+ '; ' +
              '''Y''; ' +
              Trim(FieldByName('SYNCDATE').AsString);
          SyncReviewerToMain(strRecord);
          Next;
        end;

        Showmessage('Sync completed successfully...');
      end;
    end;



end;

procedure TfrmRegistrationMain.RzButton4Click(Sender: TObject);
var
  myFile : TextFile;
  n1, n2, n3 : string;
  iRow,iCol:integer;
  ARxRecommendDescr, ARecommendStrKeys, AKeyStr: string;
  APos: Integer;
begin
iRow:=0;
AssignFile(myFile, 'F:\Workfiles\Works\CebuGems\Registration-1\SyncLog\SyncData_MAIN_03122015025739.log');
Reset(myFile);
while not Eof(myFile) do
  begin
    iRow:=iRow+1;
    iCol:=0;
    ReadLn(myFile, n1, n2, n3);
    AdvStringGrid1.AddRow;
    if length(n1) > 0 then begin
      ARecommendStrKeys := StringReplace(n1, '"', '', [rfReplaceAll]);
      while pos(';', ARecommendStrKeys) <> 0 do begin
        APos := pos(';', ARecommendStrKeys);
        AKeyStr := LeftSTr(ARecommendStrKeys, APos - 1);
        ARecommendStrKeys := midstr(ARecommendStrKeys, APos + 1, length(ARecommendStrKeys));
        AdvStringGrid1.Cells[iCol,iRow] := AKeyStr;
        iCol:=iCol+1;        
      end;
    end;

  end;
end;

procedure TfrmRegistrationMain.NewReviewee1Click(Sender: TObject);
begin
  RzPageControl1.ActivePageIndex := 0;
  frmRegistrationMain.Caption := frmRegistrationMain.Caption + ' - {VIEW/EDIT REC. NO.:' +  Trim(gridReviewerList.DataSource.DataSet.FieldByName('REVIEWERid').AsString) + '}';
  Button1Click(Sender);
end;

procedure TfrmRegistrationMain.TabSheet5Show(Sender: TObject);
  procedure InitStaff(sBranch:string);
  var
    AStaffObj: TStaffObj;
    nIndex: Integer;
  begin
    with adqTemp do begin
      Close;
      CommandTimeout := 6000; //sarma on jan.23.2013
      SQL.Text := 'select EMPLOYEECODE,DTRLINKNAME,BRANCHNAME,DEPARTMENT,USERNAME from EMPLOYEE where ACCESSREGSYS=''Y'' and BRANCHNAME = ''' + trim(sBranch) + '''' +
          ' order by DTRLINKNAME';
      Open;
      if not IsEmpty then
      begin
        cboLogUser.ClearItems;

        AStaffObj := TStaffObj.Create;
        AStaffObj.StaffKey := 0;
        AStaffObj.Name := '';
        AStaffObj.Branch := '';
        AStaffObj.Department := '';
        cboLogUser.Items.AddObject('', AStaffObj);

        First;
        while not Eof do begin
          AStaffObj := TStaffObj.Create;
          AStaffObj.StaffKey := FieldByName('EMPLOYEECODE').AsInteger;
          if (leftstr(trim(FieldByName('DEPARTMENT').AsString),4) = 'FINA') OR (trim(FieldByName('DEPARTMENT').AsString)='')  then
            AStaffObj.Name := '(A) - ' + UpperCase(trim(FieldByName('DTRLINKNAME').AsString))
          else
            AStaffObj.Name := UpperCase(FieldByName('DTRLINKNAME').AsString);
          AStaffObj.Branch := UpperCase(FieldByName('BRANCHNAME').AsString);
          AStaffObj.Department := UpperCase(FieldByName('DEPARTMENT').AsString);
          cboLogUser.Items.AddObject(AStaffObj.Name, AStaffObj);
          Next;
        end;
      end;
    end;
  end;
begin
 // if trim(cboLogBranch.Text) <> '' then
 //   InitStaff(trim(cboLogBranch.Text));

end;

procedure TfrmRegistrationMain.btnFilterClick(Sender: TObject);
var
strSQLRevList:string;
begin

  strSQLRevList:= 'select RV.REVSTATUS,RV.REVIEWERKEY, convert(char(10),RV.DATEENROLL,101) as DATEENROLLED, RNK.RANKNAME, (UPPER(RV.LASTNAME) + '', '' + UPPER(RV.FIRSTNAME)) as NAME,RV.REVIEWERid,' +
        ' UPPER(SHP.SHIPPINGNAME) as SHIPPINGNAME, UPPER(SCL.SCHOOLNAME) as SCHOOLNAME,UPPER(RV.REVSTATUS) as REVSTATUS' +
        ' from REVIEWER RV' +
        ' left join RANK RNK on RNK.RANKKEY=RV.RANKKEY' +
        ' left join SHIPPING SHP on SHP.SHIPPINGKEY=RV.SHIPPINGKEY' +
        ' left join SCHOOL SCL on SCL.SCHOOLKEY=RV.SCHOOLKEY' +
        ' where RV.reviewerid IS NOT NULL';

   if trim(cboLogUser.Text) <> 'BakiBaki' then
      strSQLRevList:= strSQLRevList + ' AND RV.BRANCHNAME = ''' + Trim(cboLogBranch.Text) + '''';

  if rzcbDateBetListTab.Checked then
     strSQLRevList:= strSQLRevList + ' and RV.DATEENROLL >= ''' + formatdatetime('yyyy-mm-dd',edtFilterDateStart.DateTime) + ''' and RV.DATEENROLL<=''' + formatdatetime('yyyy-mm-dd',edtFilterDateEnd.DateTime) + '''';
 if trim(edtFilterName.Text) <> '' then
    strSQLRevList:= strSQLRevList + ' and (RV.firstname + '' '' + RV.lastname like ''%' + trim(edtFilterName.Text) + '%'')';
  if trim(edtFilterComp.Text) <> '' then
    strSQLRevList := strSQLRevList + ' and (SHP.SHIPPINGNAME like ''%' + trim(edtFilterComp.Text) + '%'')';
  if trim(edtFilterSchool.Text) <> '' then
    strSQLRevList:= strSQLRevList + ' and (SCL.SCHOOLNAME like ''%' + trim(edtFilterSchool.Text) + '%'')';
  if trim(cbFilterStatus.Text) <> 'ALL' then
    strSQLRevList:= strSQLRevList + ' and RV.REVSTATUS=''' + trim(cbFilterStatus.Text) + '''';


  strSQLRevList:= strSQLRevList + ' order by RV.DATEENROLL DESC';

  //showmessage(strSQLRevList);

  with adoReviewerList do
  begin
    Close;
    Connection := ADOConn;
    CommandText := strSQLRevList;
    Open;
  end;
  if adoReviewerList.RecordCount>0 then
        main_rzPanelMainMenu.Caption:= inttostr(adoReviewerList.RecordCount) + ' results found.'
  else
        main_rzPanelMainMenu.Caption:=  '0 results found.';
  SetEndorsementGrid;
  gridReviewerList.Refresh;
  pageSearchResults.ActivePageIndex := 0;
end;

procedure TfrmRegistrationMain.btnCreateEndHistClick(Sender: TObject);
var
strCharge:string;
strInc:string;
begin

    if (Trim(edtEndHistToBranch.Text)='') then
    begin
      Application.MessageBox('Please enter branch to endorse enrolee to complete your transaction.', 'ENDORSEMENT', MB_OK + MB_ICONERROR);
      edtEndHistToBranch.SetFocus;
      edtEndHistToBranch.DroppedDown;
      exit;
    end;

    if (Trim(edtEndHistDate.Text)='') then
    begin
      Application.MessageBox('Please enter date of endorsement to complete your transaction.', 'ENDORSEMENT', MB_OK + MB_ICONERROR);
      edtEndHistDate.SetFocus;
      edtEndHistDate.DropButtonVisible:=True;
      exit;
    end;

   if Trim(edtEndHistKey.Text) = '' then
   begin
     with TADOCommand.Create(nil) do
     try
       Connection :=  self.ADOConn;
       CommandText := 'INSERT INTO ENDORSEMENTHISTORY (ENDORSEMENTDATE,REVIEWERKEY,FROMBRANCH,TOBRANCH,PREPAREDBY,REMARKS,AMTCRFROMBRANCH,AMTCRTOBRANCH,ORIGAMTBEFOREEND,AMTPERFRBRANCH,AMTPERTOBRANCH) VALUES (''' +
                trim(edtEndHistDate.Text) + ''',' +
                adoReviewerTable.FieldByName('REVIEWERKEY').AsString + ',''' +
                trim(cboLogBranch.Text) + ''',''' +
                TRIM(edtEndHistToBranch.Text) + ''',''' +
                TRIM(cboLogUser.Text) + ''',''' +
                TRIM(edtEndHistRemarks.Text) + ''',' +
                FloatToStr(rzCreAmtFrom.Value) + ',' +
                FloatToStr(rzBalAmt.Value) + ',' +
                FloatToStr(StrToFloat(StringReplace(trim(rzLblOrigAmt.Caption), ',', '',[rfReplaceAll, rfIgnoreCase]))) + ',' +
                IntToStr(rzSpinPerFrom.IntValue) + ',' +
                IntToStr(100-rzSpinPerFrom.IntValue) + ')';
       Execute;
     finally
       Free;
     end;

      with TADOCommand.Create(nil) do
      try
        Connection :=  self.ADOConn;
        CommandText := 'EXEC PROC_CG_UPDATE_TABLE_PROC ''REVIEWER'',''REVIEWERKEY'',''ENDORSEDFLAG'',' + adoReviewerTable.FieldByName('REVIEWERKEY').AsString + ',2,''Y''';
        Execute;
      finally
        Free;
      end;

      with TADOCommand.Create(nil) do
      try
        Connection :=  self.ADOConn;
        CommandText := 'EXEC PROC_CG_UPDATE_TABLE_PROC ''REVIEWER'',''REVIEWERKEY'',''RFREMAINING'',' + adoReviewerTable.FieldByName('REVIEWERKEY').AsString + ',1,' + FloatToStr(rzBalAmt.Value) ;
        Execute;
      finally
        Free;
      end;
      

   ShowMessage('Endorsement successfully created...');
   end
   else
   begin

     with TADOCommand.Create(nil) do
     try
       Connection :=  self.ADOConn;
       //strQuery
       CommandText := 'UPDATE ENDORSEMENTHISTORY SET ENDORSEMENTDATE=''' + trim(edtEndHistDate.Text) + ''',REVIEWERKEY=' + TRIM(adoReviewerTable.FieldByName('REVIEWERKEY').AsString) + ',FROMBRANCH=''' + trim(cboLogBranch.Text) +
                ''',TOBRANCH=''' + TRIM(edtEndHistToBranch.Text) + ''',PREPAREDBY=''' + TRIM(cboLogUser.Text) +
                ''',REMARKS=''' + TRIM(edtEndHistRemarks.Text) + ''',AMTCRFROMBRANCH=' + FloatToStr(rzCreAmtFrom.Value) +
                ',AMTCRTOBRANCH=' + FloatToStr(rzBalAmt.Value) + ',ORIGAMTBEFOREEND=' + FloatToStr(StrToFloat(StringReplace(trim(rzLblOrigAmt.Caption), ',', '',[rfReplaceAll, rfIgnoreCase]))) +
                ',AMTPERFRBRANCH=' + IntToStr(rzSpinPerFrom.IntValue) + ',AMTPERTOBRANCH=' + IntToStr(100-rzSpinPerFrom.IntValue) +
                ' WHERE ENDORSEMENTHISTORYKEY=' + trim(edtEndHistKey.Text);
       Execute;

     finally
       Free;
     end;

      with TADOCommand.Create(nil) do
      try
        Connection :=  self.ADOConn;
        CommandText := 'EXEC PROC_CG_UPDATE_TABLE_PROC ''REVIEWER'',''REVIEWERKEY'',''RFREMAINING'',' + adoReviewerTable.FieldByName('REVIEWERKEY').AsString + ',1,' + FloatToStr(rzBalAmt.Value) ;
        Execute;
      finally
        Free;
      end;

   ShowMessage('Endorsement successfully update...');



   end;


    intReportCode:=3;
    strCharge:='';
    strInc:='';
    if trim(adoReviewerTable.FieldByName('REVIEWERKEY').AsString) <> '' then
    begin
       with adoPaymentDetails do
       begin
          close;
          Connection  := Self.adoConn;
          CommandText := 'select PAYMENTARNO,PAYMENTDATE,convert(varchar,cast(PAYMENTAMOUNT as money),-1) as PAYMENTAMOUNT,' +
                ' convert(varchar,cast(PAYMENTBAL as money),-1) as PAYMENTBAL,CHARGETO FROM PAYMENT ' +
                ' WHERE REVIEWERKEY = ' + TRIM(adoReviewerTable.FieldByName('REVIEWERKEY').AsString);
          Open;

          if not IsEmpty then
          begin
            first;
            while not Eof do
            begin
              if TRIM(FieldByName('CHARGETO').AsString) <> '' then
              begin
                Last;
                strCharge:= '(' + uppercase(TRIM(FieldByName('CHARGETO').AsString)) + ' CHARGE)'
              END;
            next;
            end;
          end;
       end;

       if Trim(adoReviewerTable.fieldbyname('GREENBOOK').AsString) = 'Y' then
                strInc:=strInc+'GREENBOOK, ';
       if Trim(adoReviewerTable.fieldbyname('PAMPHLET').AsString) = 'Y' then
                strInc:=strInc+'PAMPHLET, ';
       if Trim(adoReviewerTable.fieldbyname('COLREG').AsString) = 'Y' then
                strInc:=strInc+'COLREG, ';
       if Trim(adoReviewerTable.fieldbyname('FORMULA').AsString) = 'Y' then
                strInc:=strInc+'FORMULA, ';
       if Trim(adoReviewerTable.fieldbyname('ENGINEBOOK').AsString) = 'Y' then
                strInc:=strInc+'ENGINEBOOK, ';
       if Trim(adoReviewerTable.fieldbyname('NOTEBOOK').AsString) = 'Y' then
                strInc:=strInc+'NOTEBOOK, ';
       if Trim(adoReviewerTable.fieldbyname('BAG').AsString) = 'Y' then
                strInc:=strInc+'BAG, ';
       if Trim(adoReviewerTable.fieldbyname('POLOSHIRT1').AsString) = 'Y' then
                strInc:=strInc+'POLO SHIRT1, ';
       if Trim(adoReviewerTable.fieldbyname('POLOSHIRT2').AsString) = 'Y' then
                strInc:=strInc+'POLO SHIRT2, ';
       if Trim(adoReviewerTable.fieldbyname('IDCARD').AsString) = 'Y' then
                strInc:=strInc+'ID CARD, ';
       if Trim(adoReviewerTable.fieldbyname('IDSLING').AsString) = 'Y' then
                strInc:=strInc+'ID SLING, ';
       if Trim(adoReviewerTable.fieldbyname('TSHIRT1').AsString) = 'Y' then
                strInc:=strInc+'T-SHIRT1, ';
       if Trim(adoReviewerTable.fieldbyname('TSHIRT2').AsString) = 'Y' then
                strInc:=strInc+'T-SHIRT2, ';
       if Trim(adoReviewerTable.fieldbyname('TSHIRT1').AsString) = 'Y' then
                strInc:=strInc+'T-SHIRT3, ';


       fltRunBalance := adoReviewerTable.fieldbyname('REVIEWERFEE').AsVariant;
       QRLESREVID.Caption := 'REVIEWER ID: ' + strAbbr + '-' + RightStr(trim(adoReviewerTable.FieldByName('REVIEWERid').AsString),4);
       //lblSatBranch.Caption := Trim(adoReviewerTable.fieldbyname('SATBRANCH').AsString);
       QRLESREVSHIPPING.Caption :=  trim(cbShipping.Text);
       //lblRemarks.Caption := trim(edtRemarks.Text);
       QRLESINCLUSIONS.Caption := trim(strInc);
       QRLESREVSCHOOL.Caption := trim(cbSchool.Text);
       QRLESREVENDORSED.Caption := trim(cbEndorser.Text);
       QRLESCHARGETO.Caption := trim(strCharge);
       QRLESBRANCHNAME.Caption := UpperCase(trim(cboLogBranch.Text) + ' BRANCH');
       QRLESFROMBRANCH.Caption := UpperCase('FROM: ' + trim(cboLogBranch.Text) + ' BRANCH');
       QRLESTOBRANCH.Caption := UpperCase('TO: ' + trim(edtEndHistToBranch.Text) + ' BRANCH');
       QRLESBRANCHNAMEADD.Caption := '';
       QRLESENDORSEMENTID.Caption := '';
       QRLESEXAMFOR.Caption :=' Exam For: ' +  trim(cbRank.Text);
       QRLESFOOTERENDORSEDBY.Caption := trim(edtEnrollOfficer.Text);
       QRLESFOOTERENDORSEDATE.Caption := 'Endorsed Date: ' + formatdatetime('yyyy/mm/dd',Now());
       QRLESENDORSEDATE.Caption := formatdatetime('yyyy/mm/dd',Now());
       QRLPRINTEDDATE.Caption := ' Printed in [' + trim(cboLogBranch.Text) + '] / ' + formatdatetime('yyyy-mm-dd hh:nn:ss',Now());
       QRLESENROLLINGOFFICER.Caption := 'Enrolling Officer : ' + trim(edtEnrollOfficer.Text);
       if trim(adoReviewerTable.fieldbyname('REVIEWERFEE').AsString) <> '' then
           QRLESREVIEWERFEE.Caption := FormatFloat('#,##0.00', adoReviewerTable.fieldbyname('REVIEWERFEE').AsVariant);
       if trim(adoReviewerTable.fieldbyname('DATEENROLL').AsString) <> '' then
           lblDate.Caption := 'Date: ' + FormatDateTime('DD MMM YYYY', adoReviewerTable.fieldbyname('DATEENROLL').AsDateTime);
       QuickRep3.Prepare;
       ConvertToPDF;
    end;

   pnlEndorsetoBranch.Visible := False;

end;

procedure TfrmRegistrationMain.btnCreateEndorsementClick(Sender: TObject);
function GetEndHistKey(iRevKey:integer):integer;
begin
      Hint :='Checking for existing endorsement...';
      with TADOQuery.Create(nil) do
      try
        Connection := self.ADOConn;
        SQL.Text := 'select * FROM ENDORSEMENTHISTORY' +
               ' WHERE REVIEWERKEY = ' + inttostr(iRevKey);
        try
          Open;
        except
          Exit;
        end;
        if not IsEmpty then
        begin
          result := FieldByName('ENDORSEMENTHISTORYKEY').AsInteger;
          edtEndHistDate.Date := FieldByName('ENDORSEMENTDATE').AsDateTime;
          edtEndHistToBranch.Text:= trim(FieldByName('TOBRANCH').AsString);
          edtEndHistRemarks.Text:= trim(FieldByName('REMARKS').AsString);
          rzSpinPerFrom.Value := FieldByName('AMTPERFRBRANCH').AsInteger;
          rzTrackCRPer.Position:= StrToInt(FormatFloat('###0',rzSpinPerFrom.Value/10));
          rzLblOrigAmt.Caption:= FormatFloat('#,##0.00',FieldByName('ORIGAMTBEFOREEND').AsVariant);
          rzCreAmtFrom.Value := FieldByName('AMTCRFROMBRANCH').AsVariant;
          rzBalAmt.Value := FieldByName('AMTCRTOBRANCH').AsVariant;
        end
        else
          result := 0;

      finally
        Free;
      end;

end;

procedure LoadDefBranches;
begin
      Hint:='Loading branches...';
      with TADOQuery.Create(nil) do
      try
        Connection := self.ADOConn;  
        SQL.Text := 'select UPPER(BRANCH) as BRANCH FROM REFERENCEID WHERE BRANCH NOT LIKE ''%' + trim(cboLogBranch.Text) + '%''';
        try
          Open;
        except
          Exit;
        end;
        if not IsEmpty then
        begin
            edtEndHistToBranch.ClearItems;
            First;
            While not Eof do
            begin
                edtEndHistToBranch.Add(trim(FieldByName('BRANCH').AsString));
            next;
            end;
        end
        else
          Showmessage('Please contact your administrator for branch listings.');

      finally
        Free;
      end;

end;

procedure SetToDefaultEntries;
begin

  edtEndHistKey.Text:='';
  rzSpinPerFrom.Value := 30;
  rzTrackCRPer.Position:= 3;
  rzLblOrigAmt.Caption:= '';
  rzCreAmtFrom.Value := 0;
  rzBalAmt.Value := 0;

end;
var
    DefStrCurrRFAmount:string;
    DefFltCurrRFAmount:Variant;
begin
    if pnlQuickPayment.Visible then Exit;

    DefStrCurrRFAmount:='0.00';
    DefFltCurrRFAmount:=0;
    SetToDefaultEntries;

    if (trim(adoReviewerTable.FieldByName('ENDORSEDFLAG').AsString) <> 'Y') and (trim(adoReviewerTable.FieldByName('RFREMAINING').AsString)='')  then
    begin
        showmessage('Please click save button to update important fields for endorsement...');
        //rzToolbarRegEntry_btnCreateEnd.i;
        exit;
    end else
    begin
        if trim(adoReviewerTable.FieldByName('RFREMAINING').AsString)='' then
            DefStrCurrRFAmount:=FormatFloat('#,##0.00',adoReviewerTable.FieldByName('REVIEWERFEE').AsVariant)
        else
            DefStrCurrRFAmount:=FormatFloat('#,##0.00',adoReviewerTable.FieldByName('RFREMAINING').AsVariant);
    end;
    Self.Hint:='Please wait while endorsement form is loading.';
    if trim(adoReviewerTable.FieldByName('REVIEWERKEY').AsString) <> '' then
    begin
      groupboxEndHist.Caption := 'New Endorsement from - ( ' + trim(cboLogBranch.Text) + ' ):';
      LoadDefBranches;
      if TMenuItem(Sender).Tag=2 then
      begin
        edtEndHistKey.Text:=inttostr(GetEndHistKey(adoReviewerTable.FieldByName('REVIEWERKEY').AsInteger));
        Hint:='Existing endorsement is being loaded...';
      end
      else
      begin
        edtEndHistKey.Text:='';
        rzSpinPerFrom.Value := 30;
        rzTrackCRPer.Position:= 3;
        rzLblOrigAmt.Caption:= Trim(DefStrCurrRFAmount);
        DefFltCurrRFAmount:=StrToFloat(StringReplace(trim(rzLblOrigAmt.Caption), ',', '',[rfReplaceAll, rfIgnoreCase]));        
        rzCreAmtFrom.Value := ((DefFltCurrRFAmount*30)/100);
        rzBalAmt.Value := (DefFltCurrRFAmount-rzCreAmtFrom.Value);
        Hint:='New endorsement form is created...';
      end;
      pnlEndorsetoBranch.Visible := True;
      edtEndHistDate.SetFocus;
      edtEndHistDate.DropButtonVisible:=True;
      Hint:='Endorsement form is open.';    
    end;
end;

procedure TfrmRegistrationMain.Timer1Timer(Sender: TObject);
begin
  SetEndorsementGrid;
end;

procedure TfrmRegistrationMain.RzButton8Click(Sender: TObject);
begin
    pnlEndorsetoBranch.Visible := False;
end;

procedure TfrmRegistrationMain.FormClose(Sender: TObject;
  var Action: TCloseAction);
begin
  if iPostData=False then
  begin
        if Application.MessageBox('Do you want to save this record?',
            'Save Record', MB_ICONINFORMATION + MB_YESNO) = IDYES then
            Button3Click(Sender)
        else
        begin
            adoReviewerTable.Cancel;
            iPostData:=True;
        end;

  end;
end;

procedure TfrmRegistrationMain.gridReviewerListCellClick(Column: TColumn);
begin
    NewReviewee1.Enabled:=gridReviewerList.SelectedRows.Count=1;
    Prepare1.Enabled:=gridReviewerList.SelectedRows.Count>1;
end;

procedure TfrmRegistrationMain.Prepare1Click(Sender: TObject);
begin

    if adoReviewerList.RecordCount>0 then
    begin
      adoReviewerList.First;
      while not adoReviewerList.Eof do
      begin
         //if gridReviewerList.SelectedIndex
         if gridReviewerList.SelectedRows.CurrentRowSelected then
           showmessage(trim(adoReviewerList.fieldbyname('reviewerkey').AsString));
         adoReviewerList.Next;
      end;
    end;

end;

procedure TfrmRegistrationMain.rzSpinPerFromChange(Sender: TObject);
var
    xOrigVal:Variant;
begin

    if trim(rzLblOrigAmt.Caption) <>'' then
    begin
      xOrigVal:= StrToFloat(StringReplace(trim(rzLblOrigAmt.Caption), ',', '',[rfReplaceAll, rfIgnoreCase]));
      rzTrackCRPer.Position:= StrToInt(FormatFloat('###0',rzSpinPerFrom.Value/10));
      rzCreAmtFrom.Value :=  ((xOrigVal*rzSpinPerFrom.Value)/100);
      rzBalAmt.Value := (xOrigVal-rzCreAmtFrom.Value);
    end;
end;

procedure TfrmRegistrationMain.rzTrackCRPerClick(Sender: TObject);
begin
    rzSpinPerFrom.IntValue:= (rzTrackCRPer.Position*10);
end;

procedure TfrmRegistrationMain.RzBitBtn2Click(Sender: TObject);
function DynamicTableUpdatefn(sTableName:string;sTablePK:string;sUpdateFName:string;iPKVal:integer;iUpdateFType:integer;sUpdateFValue:string):boolean;
begin

      with TADOCommand.Create(nil) do
      try
        Connection :=  self.ADOConn;
        CommandText := 'EXEC PROC_CG_UPDATE_TABLE_PROC ''' + sTableName + ''',''' + sTablePK + ''',''' + sUpdateFName + ''',' + inttostr(iPKVal) + ',' + inttostr(iUpdateFType) + ',''' + sUpdateFValue + '''';
        try
            Execute;
            Result:=True;
        except
            Result:=False;
        end;
      finally
        Free;
      end;

end;

var
strReviewerKey,strEndHistKey:string;
bUpdateResult:boolean;
begin
    strReviewerKey := trim(gridEndorsements.Cells[6,gridEndorsements.GetRealRow]);
    strEndHistKey := trim(gridEndorsements.Cells[5,gridEndorsements.GetRealRow]);
    bUpdateResult:=False;
    //ShowMessage(strReviewerKey);

    if strEndHistKey<>'' then
    begin
        with TADOCommand.Create(nil) do
        try
         Connection :=  self.ADOConn;
         //strQuery
         CommandText := 'UPDATE ENDORSEMENTHISTORY SET ACCEPTEDDATE=''' + FormatDateTime('MM-DD-YYYY',Now()) + ''',ACCEPTEDBY=''' + TRIM(cboLogUser.Text) + '''' +
                  ' WHERE ENDORSEMENTHISTORYKEY=' + trim(strEndHistKey);
         Execute;

        finally
         Free;
        end;

      bUpdateResult:=DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','ENDORSEDFLAG', strtoint(strReviewerKey), 2,'N');
      bUpdateResult:=DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','BRANCHNAME', strtoint(strReviewerKey), 2,TRIM(cboLogBranch.Text));
      bUpdateResult:=DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','MODIFIEDBY', strtoint(strReviewerKey), 2,TRIM(cboLogUser.Text));
      bUpdateResult:=DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','MODIFIEDDATE', strtoint(strReviewerKey), 2,FormatDateTime('MM-DD-YYYY',Now()));      

      ShowMessage('Endorsement has been accepted from this branch...');

    end;

    btnFilterClick(Self);

end;

procedure TfrmRegistrationMain.rzMainBtnExitClick(Sender: TObject);
begin
    Close;
end;

procedure TfrmRegistrationMain.rzMainBtnRegisterClick(Sender: TObject);
begin
    RzPageControl1.ActivePageIndex:=0;
    iPostData:=True;
    Button1Click(Sender);    
end;

procedure TfrmRegistrationMain.rzMainBtnSearchClick(Sender: TObject);
begin
    RzPageControl1.ActivePageIndex:=1;
end;

procedure TfrmRegistrationMain.TabSheet2Click(Sender: TObject);
begin
    RzPageControl1.ActivePageIndex:=1;
end;

procedure TfrmRegistrationMain.rzMainBtnPrintClick(Sender: TObject);
begin
    RzPageControl1.ActivePageIndex:=3;
    iPostData:=False;
end;

procedure TfrmRegistrationMain.rzMainBtnLogoutClick(Sender: TObject);
begin
    RzPageControl1.ActivePageIndex:=4;
    main_rzPanelMainMenu.Visible:=(RzPageControl1.ActivePageIndex<>4);
    main_rzStatusBarMain.Visible:=(RzPageControl1.ActivePageIndex<>4);
    cboLogUser.Text:='';
    cboLogUser.SetFocus;
    cboLogUser.DroppedDown:=True;
    iPostData:=False;
end;

procedure TfrmRegistrationMain.rzMainBtnBillingClick(Sender: TObject);
begin
    RzPageControl1.ActivePageIndex:=7;
    iPostData:=False;
end;

procedure TfrmRegistrationMain.TabSheet9Show(Sender: TObject);
begin
    IncShippingList2BillToDropdown(0,'');
end;

procedure TfrmRegistrationMain.rzbtneditSelectBillToButtonClick(
  Sender: TObject);
begin
    if iFlagClickBtn=false then IncShippingList2BillToDropdown(0,'');
    rzcomboboxBillToDropdown.Visible:=True;
    rzcomboboxBillToDropdown.SetFocus;
    rzcomboboxBillToDropdown.DroppedDown:=True;
end;

procedure TfrmRegistrationMain.rzbtneditSelectBillToAltBtnClick(
  Sender: TObject);
begin
    if iFlagClickBtn then
    begin
        IncShippingList2BillToDropdown(1,trim(rzbtneditSelectBillTo.Text));
        rzbtneditSelectBillToButtonClick(Sender);
        iFlagClickBtn:=False;
    end else
    begin
        iFlagClickBtn:=True;
        rzbtneditSelectBillTo.Text:='(TYPE BILL TO SEARCH HERE)';
        rzbtneditSelectBillTo.SetFocus;
        rzbtneditSelectBillTo.SelectAll;
    end;


end;

procedure TfrmRegistrationMain.IncShippingList2BillToDropdown(iFilter:integer;sFilter:String);
var
    strSQL:string;
begin
      with TADOQuery.Create(nil) do
      try
        Connection := self.ADOConn;
        //SQL.Text := 'select (UPPER(format(SHIPPINGKEY,''S-0000'')) + '' - '' + UPPER(SHIPPINGNAME)) AS BillFullName from SHIPPING order by SHIPPINGNAME';
        strSQL := 'select SHIPPINGKEY,UPPER(SHIPPINGNAME) AS SHIPPINGNAME from SHIPPING';
        if iFilter<>0 then
            strSQL:= strSQL + ' where SHIPPINGNAME like ''%' + sFilter + '%''';
        SQL.Text := strSQL + ' order by SHIPPINGNAME';
        try
          Open;
        except
          Exit;
        end;
        if not IsEmpty then
        begin
            rzcomboboxBillToDropdown.ClearItems;
            rzcomboboxBillToDropdown.ClearItemsValues;
            rzcPassersComlist.ClearItems;
            rzcPassersComlist.ClearItemsValues;
            First;
            While not Eof do
            begin
                with rzcomboboxBillToDropdown do
                begin
                    AddItemValue(trim(FieldByName('SHIPPINGNAME').AsString),trim(FieldByName('SHIPPINGKEY').AsString));
                end;
                with rzcPassersComlist do
                begin
                    AddItemValue(trim(FieldByName('SHIPPINGNAME').AsString),trim(FieldByName('SHIPPINGKEY').AsString));
                end;

            next;
            end;
        end
        else
          Showmessage('Please contact your administrator for shipping listings.');



      finally
        Free;
      end;

      with TADOQuery.Create(nil) do
      try
        Connection := self.ADOConn;
        strSQL := 'select distinct BRANCH from REFERENCEID';
        SQL.Text := strSQL + ' order by BRANCH';
        try
          Open;
        except
          Exit;
        end;
        if not IsEmpty then
        begin
            rzcomboPassersBRanch.ClearItems;
            rzcomboPassersBRanch.ClearItemsValues;
            First;
            While not Eof do
            begin
                with rzcomboPassersBRanch do
                begin
                    AddItemValue(trim(FieldByName('BRANCH').AsString),trim(FieldByName('BRANCH').AsString));
                end;
            next;
            end;
        end
        else
          Showmessage('Please contact your administrator for BRANCH listings.');

      finally
        Free;
      end;


end;


procedure TfrmRegistrationMain.rzcomboboxBillToDropdownSelect(
  Sender: TObject);
procedure SetParticularsChecklist(iPK:integer);
function fnIncMyCounter(iNumber:integer):integer;
begin
    iVarCounter:=iNumber+1;
    Result:=iVarCounter;
end;

procedure InitReviewerList(iPkVal:integer;sTableName:string);
var
  ARevListObj: TDropDownListObj;
  nIndex: Integer;
  strSQLSource:string;
begin
  with adqTemp do begin
    Close;
    CommandTimeout := 6000;
    strSQLSource :='select RV.REVIEWERKEY, convert(char(10),RV.DATEENROLL,101) as DATEENROLLED, RNK.RANKNAME, (UPPER(RV.LASTNAME) + '', '' + UPPER(RV.FIRSTNAME)) as NAME,RV.REVIEWERid, REF.ABBR,' +
            ' UPPER(SHP.SHIPPINGNAME) as SHIPPINGNAME, UPPER(SCL.SCHOOLNAME) as SCHOOLNAME,UPPER(RV.REVSTATUS) as REVSTATUS,RV.REVIEWERFEE' +
            ' from REVIEWER RV' +
            ' left join RANK RNK on RNK.RANKKEY=RV.RANKKEY' +
            ' left join SHIPPING SHP on SHP.SHIPPINGKEY=RV.SHIPPINGKEY' +
            ' left join SCHOOL SCL on SCL.SCHOOLKEY=RV.SCHOOLKEY' +
            ' left join REFERENCEID REF ON REF.BRANCH=RV.BRANCHNAME AND REF.MODULENAME=''REGISTRATION''';

    if sTableName='SHIPPING' then
        strSQLSource := strSQLSource + ' where RV.SHIPPINGKEY=' + inttostr(iPkVal) + ' order by NAME'
    else
        strSQLSource := strSQLSource + ' where RV.SCHOOLKEY=' + inttostr(iPkVal) + ' order by NAME';
    SQL.Text:= strSQLSource;
    Open;
    if not IsEmpty then
    begin
      First;
      rzchecklistReviewer.Clear;
      while not Eof do begin
        ARevListObj := TDropDownListObj.Create;
        ARevListObj.PK := FieldByName('REVIEWERKEY').AsInteger;
        ARevListObj.StringName := UpperCase(trim(FieldByName('NAME').AsString));
        ARevListObj.FltAmount := FieldByName('REVIEWERFEE').AsVariant;
        rzchecklistReviewer.Items.AddObject(ARevListObj.StringName,ARevListObj);
        Next;
      end;
    end;
  end;
end;
begin

    InitReviewerList(iPK,'SHIPPING');

{
      with TADOQuery.Create(nil) do
      try
        Connection := self.ADOConn;
        strSQL:= 'select RV.REVIEWERKEY, convert(char(10),RV.DATEENROLL,101) as DATEENROLLED, RNK.RANKNAME, (UPPER(RV.LASTNAME) + '', '' + UPPER(RV.FIRSTNAME)) as NAME,RV.REVIEWERid, REF.ABBR,' +
              ' UPPER(SHP.SHIPPINGNAME) as SHIPPINGNAME, UPPER(SCL.SCHOOLNAME) as SCHOOLNAME,UPPER(RV.REVSTATUS) as REVSTATUS' +
              ' from REVIEWER RV' +
              ' left join RANK RNK on RNK.RANKKEY=RV.RANKKEY' +
              ' left join SHIPPING SHP on SHP.SHIPPINGKEY=RV.SHIPPINGKEY' +
              ' left join SCHOOL SCL on SCL.SCHOOLKEY=RV.SCHOOLKEY' +
              ' left join REFERENCEID REF ON REF.BRANCH=RV.BRANCHNAME AND REF.MODULENAME=''REGISTRATION'''+
              ' where RV.SHIPPINGKEY = '+ inttostr(iPK);
        SQL.Text := strSQL + ' order by RV.REVIEWERKEY desc';
        try
          Open;
        except
          Exit;
        end;
        if not IsEmpty then
        begin
            iVarCounter:=0;
            with rzchecklistReviewer do
            begin
                Clear;
                First;
                while not Eof do
                begin
                    Items.Append(UpperCase(trim(FieldByName('NAME').AsString)));
                    ivarcounter:=ivarcounter+1;
                Next;
                end;
            end;
        end else
          Showmessage('Please contact your administrator for particulars listings.');

      finally
        Free;
      end;
      }
end;

procedure SetBillToInfoValues(iPKey:integer);
function fnIncMyCounter(iNumber:integer):integer;
begin
    iVarCounter:=iNumber+1;
    Result:=iVarCounter;
end;

var
    strSQL:string;
    iNdex:integer;
    tsBlank:TStrings;
begin
      iVarCounter:=0;

      with TADOQuery.Create(nil) do
      try
        Connection := self.ADOConn;
        //SQL.Text := 'select (UPPER(format(SHIPPINGKEY,''S-0000'')) + '' - '' + UPPER(SHIPPINGNAME)) AS BillFullName from SHIPPING order by SHIPPINGNAME';
        strSQL := 'select SHIPPINGKEY,UPPER(SHIPPINGNAME) AS SHIPPINGNAME,ADDRESS,REMARKS,BRANCHENTERED,' +
            ' DATEENTERED,ENTEREDBY,DefContactPerson,DefCPPosition,DefCPPhone,DefCPMobile,DefCPEmail,STATUS from SHIPPING' +
            ' where SHIPPINGKEY=' + inttostr(iPKey);
        strSQL := strSQL + ' order by SHIPPINGNAME';
        SQL.Text := strSQL;
        try
          Open;
        except
          Exit;
        end;
        if not IsEmpty then
        begin
            rzedtBillToInfoName.Text:= UpperCase(trim(FieldByName('SHIPPINGNAME').AsString));
            rzedtBillToInfoAddress.Text:= trim(FieldByName('ADDRESS').AsString);
            rzedtBillToInfoConPerson.Text:= UpperCase(trim(FieldByName('DefContactPerson').AsString));
            rzedtBillToInfoPosition.Text:= trim(FieldByName('DefCPPosition').AsString);
            rzedtBillToInfoMobile.Text:= trim(FieldByName('DefCPMobile').AsString);
            rzedtBillToInfoEmail.Text:= trim(FieldByName('DefCPEmail').AsString);
            rzedtBillToInfoOffNumber.Text:= trim(FieldByName('DefCPPhone').AsString);
            iVarCounter:=0;
            rzmemoBillToName.Clear;
            if trim(FieldByName('SHIPPINGNAME').AsString)<>'' then
                rzmemoBillToName.Lines.Insert((fnIncMyCounter(ivarcounter)-1),UpperCase(trim(FieldByName('SHIPPINGNAME').AsString)));
            rzmemoBillToName.JumpTo(0,0);
            iVarCounter:=0;
            rzmemoBillToDetails.Clear;
            if trim(FieldByName('DefContactPerson').AsString)<>'' then
                rzmemoBillToDetails.Lines.Insert((fnIncMyCounter(ivarcounter)-1),UpperCase(trim(FieldByName('DefContactPerson').AsString)));
            if trim(FieldByName('DefCPPosition').AsString)<>'' then
                rzmemoBillToDetails.Lines.Insert((fnIncMyCounter(ivarcounter)-1),trim(FieldByName('DefCPPosition').AsString));
            if trim(FieldByName('ADDRESS').AsString)<>'' then
                rzmemoBillToDetails.Lines.Insert((fnIncMyCounter(ivarcounter)-1),trim(FieldByName('ADDRESS').AsString));
            if trim(FieldByName('DefCPPhone').AsString)<>'' then
                rzmemoBillToDetails.Lines.Insert((fnIncMyCounter(ivarcounter)-1),'Tel. No. ' +trim(FieldByName('DefCPPhone').AsString));
            if trim(FieldByName('DefCPMobile').AsString)<>'' then
                rzmemoBillToDetails.Lines.Insert((fnIncMyCounter(ivarcounter)-1),'Mobile ' +trim(FieldByName('DefCPMobile').AsString));
            if trim(FieldByName('DefCPEmail').AsString)<>'' then
                rzmemoBillToDetails.Lines.Insert((fnIncMyCounter(ivarcounter)-1),'Email ' +trim(FieldByName('DefCPEmail').AsString));
            rzmemoBillToDetails.JumpTo(0,0);
        end else
          Showmessage('Please contact your administrator for shipping listings.');

      finally
        Free;
      end;


end;
begin
    rzbtneditSelectBillTo.Text := Trim(rzcomboboxBillToDropdown.Text);
    SetBillToInfoValues(StrToInt(rzcomboboxBillToDropdown.Value));
    SetParticularsChecklist(StrToInt(rzcomboboxBillToDropdown.Value));
    rzeditPK.Text:=rzcomboboxBillToDropdown.Value;
    rzbtneditSelectBillTo.SetFocus;
    rzcomboboxBillToDropdown.Visible:=False;
end;

procedure TfrmRegistrationMain.rzbitbtnBillToInfoButtonClick(
  Sender: TObject);
function DynamicTableUpdatefn(sTableName:string;sTablePK:string;sUpdateFName:string;iPKVal:integer;iUpdateFType:integer;sUpdateFValue:string):boolean;
begin

      with TADOCommand.Create(nil) do
      try
        Connection :=  self.ADOConn;
        CommandText := 'EXEC PROC_CG_UPDATE_TABLE_PROC ''' + sTableName + ''',''' + sTablePK + ''',''' + sUpdateFName + ''',' + inttostr(iPKVal) + ',' + inttostr(iUpdateFType) + ',''' + sUpdateFValue + '''';
        try
            Execute;
            Result:=True;
        except
            Result:=False;
        end;
      finally
        Free;
      end;

end;
begin
    if rzbitbtnBillToInfoButton.Caption='Show [Bill To] Information' then
    begin
        rzGroupUpdateBillToInfo.Enabled:=true;
        rzbitbtnBillToInfoButton.Caption:='Click to Save Changes';
        rzbitbtnBillToInfoButton.Font.Color:=clGreen;
    end else
    begin
        DynamicTableUpdatefn('SHIPPING','SHIPPINGKEY','SHIPPINGNAME', strtoint(trim(rzeditPK.Text)), 2,trim(rzedtBillToInfoName.Text));
        DynamicTableUpdatefn('SHIPPING','SHIPPINGKEY','ADDRESS', strtoint(trim(rzeditPK.Text)), 2,trim(rzedtBillToInfoAddress.Text));
        DynamicTableUpdatefn('SHIPPING','SHIPPINGKEY','DefContactPerson', strtoint(trim(rzeditPK.Text)), 2,trim(rzedtBillToInfoConPerson.Text));
        DynamicTableUpdatefn('SHIPPING','SHIPPINGKEY','DefCPPosition', strtoint(trim(rzeditPK.Text)), 2,trim(rzedtBillToInfoPosition.Text));
        DynamicTableUpdatefn('SHIPPING','SHIPPINGKEY','DefCPPhone', strtoint(trim(rzeditPK.Text)), 2,trim(rzedtBillToInfoOffNumber.Text));
        DynamicTableUpdatefn('SHIPPING','SHIPPINGKEY','DefCPMobile', strtoint(trim(rzeditPK.Text)), 2,trim(rzedtBillToInfoMobile.Text));
        DynamicTableUpdatefn('SHIPPING','SHIPPINGKEY','DefCPEmail', strtoint(trim(rzeditPK.Text)), 2,trim(rzedtBillToInfoEmail.Text));
        rzGroupUpdateBillToInfo.Enabled:=false;
        rzbitbtnBillToInfoButton.Caption:='Show [Bill To] Information';
        rzbitbtnBillToInfoButton.Font.Color:=clBlack;
    end;

end;

procedure TfrmRegistrationMain.rzchkSelectAllParticularsClick(
  Sender: TObject);
var
    i:integer;
    xObj:TDropDownListObj;
begin
    for i:=0 to rzchecklistReviewer.Items.Count-1 do
    begin
        rzchecklistReviewer.ItemChecked[i]:= (rzchkSelectAllParticulars.Checked);
    end;


end;

procedure TfrmRegistrationMain.rzMainBtnPassersClick(Sender: TObject);
begin
    RzPageControl1.ActivePageIndex:=8;
    iPostData:=True;
end;

procedure TfrmRegistrationMain.rzMainBtnRebatesClick(Sender: TObject);
begin
    RzPageControl1.ActivePageIndex:=6;
    iPostData:=True;
end;

procedure TfrmRegistrationMain.rzMainBtnAdminClick(Sender: TObject);
begin
    RzPageControl1.ActivePageIndex:=9;
    iPostData:=True;
end;

procedure TfrmRegistrationMain.rzicbUserListSelect(Sender: TObject);
procedure ShowUserModules(iPKey:STRING);
var
    strSQL:string;
    iNdex:integer;
    tsBlank:TStrings;
    AModuleListObj:TUserRightsObj;
begin
      iVarCounter:=0;

      with TADOQuery.Create(nil) do
      try
        Connection := self.ADOConn;
        //SQL.Text := 'select (UPPER(format(SHIPPINGKEY,''S-0000'')) + '' - '' + UPPER(SHIPPINGNAME)) AS BillFullName from SHIPPING order by SHIPPINGNAME';
        strSQL := 'SELECT M.MODULE,E.DTRLINKNAME, UR.*' +
            ' FROM USERRIGHTS UR' +
            ' LEFT JOIN MODULE M ON M.MODULEKEY=UR.MODULEKEY' +
            ' LEFT JOIN EMPLOYEE E ON E.EMPLOYEECODE=UR.EMPLOYEECODE' +            
            ' where E.DTRLINKNAME LIKE ''%' + TRIM(iPKey) + '%''';
        strSQL := strSQL + ' order by MODULE';
        SQL.Text := strSQL;
        try
          Open;
        except
          Exit;
        end;
        
        if not IsEmpty then
        begin
            first;
            rzclAdminModuleList.Clear;
            while not Eof do begin
              AModuleListObj := TUserRightsObj.Create;
              AModuleListObj.URKey := FieldByName('USERRIGHTSKEY').AsInteger;
              AModuleListObj.EmpCode:= FieldByName('EMPLOYEECODE').AsInteger;
              AModuleListObj.ModuleName := UpperCase(trim(FieldByName('MODULE').AsString));
              AModuleListObj.CAdd:=UpperCase(trim(FieldByName('CANADD').AsString));
              AModuleListObj.CEdit:=UpperCase(trim(FieldByName('CANEDIT').AsString));
              AModuleListObj.CDelete:=UpperCase(trim(FieldByName('CANDELETE').AsString));
              AModuleListObj.CSave:=UpperCase(trim(FieldByName('CANSAVE').AsString));
              AModuleListObj.CPrint:=UpperCase(trim(FieldByName('CANPRINT').AsString));
              rzclAdminModuleList.Items.AddObject(AModuleListObj.ModuleName,AModuleListObj);
              Next;
            end;
        end else
        rzclAdminModuleList.Clear;

      finally
        Free;
      end;

end;
begin

    ShowUserModules(trim(rzicbUserList.Items.Strings[rzicbUserList.IndexOfItem(rzicbUserList.ImageComboItem[rzicbUserList.ItemIndex])]))
end;

procedure TfrmRegistrationMain.RzBitBtn4Click(Sender: TObject);
function DynamicTableUpdatefn(sTableName:string;sTablePK:string;sUpdateFName:string;iPKVal:integer;iUpdateFType:integer;sUpdateFValue:string):boolean;
begin

      with TADOCommand.Create(nil) do
      try
        Connection :=  self.ADOConn;
        CommandText := 'EXEC PROC_CG_UPDATE_TABLE_PROC ''' + sTableName + ''',''' + sTablePK + ''',''' + sUpdateFName + ''',' + inttostr(iPKVal) + ',' + inttostr(iUpdateFType) + ',''' + sUpdateFValue + '''';
        try
            Execute;
            Result:=True;
        except
            Result:=False;
        end;
      finally
        Free;
      end;

end;
var
    i:integer;
    xObj:TDropDownListObj;
    iTableUpdated:boolean;
    intBillingPK:integer;
begin

    adoBilling.APPEND;
    adoBilling.fieldbyname('BILLINGDATE').AsDateTime:= Now();
    adoBilling.fieldbyname('BRANCH').AsString:= trim(cboLogBranch.Text);
    adoBilling.fieldbyname('PREPAREDBY').AsString:= 'Marjorie S. Quijada';
    adoBilling.fieldbyname('APPROVEDBY').AsString:= 'Capt. Juan Antoine B. Dela Torre';
    adoBilling.fieldbyname('TRANSACTIONDATE').AsDateTime:= Now();
    adoBilling.fieldbyname('STATUS').AsString:= 'A';
    adoBilling.fieldbyname('CREATEDBY').AsString:= trim(cboLogUser.Text);
    adoBilling.Post;
    intBillingPK:= adoBilling.fieldbyname('BILLINGKEY').AsInteger;
    //SHOWMESSAGE(INTTOSTR(intBillingPK));
    
    for i:=0 to rzchecklistReviewer.Items.Count-1 do
    begin
        if rzchecklistReviewer.ItemChecked[i] = true then
        begin
          rzchecklistReviewer.ItemChecked[i]:= (rzchkSelectAllParticulars.Checked);
          iTableUpdated:= DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','BILLINGKEY', TDropDownListObj(rzchecklistReviewer.Items.Objects[i]).PK, 1,inttostr(intBillingPK));
          iTableUpdated:= DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','BILLAMT', TDropDownListObj(rzchecklistReviewer.Items.Objects[i]).PK, 1,FormatFloat('###0.00',TDropDownListObj(rzchecklistReviewer.Items.Objects[i]).FltAmount));          
          iTableUpdated:= DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','BILLED', TDropDownListObj(rzchecklistReviewer.Items.Objects[i]).PK, 2,'Y');
          IF DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','BILLED', TDropDownListObj(rzchecklistReviewer.Items.Objects[i]).PK, 2,'Y')= true then
              main_rzStatusBarMain.Hint :=INTTOSTR(intBillingPK) + ' -- ' + FormatFloat('Php #,##0.00',TDropDownListObj(rzchecklistReviewer.Items.Objects[i]).FltAmount);
        end;
    end;

    QuickRep4.Preview;


end;

procedure TfrmRegistrationMain.SetPassersGrid;
var
iRowCounter:integer;
strSQL:string;
begin
    strSQL:='SELECT (UPPER(RV.LASTNAME) + '', '' + UPPER(RV.FIRSTNAME)) as NAME,RV.REVSTATUS,LOWER(RV.EMAIL) AS EMAIL' +
            ',RV.ADDRESS,RV.REVIEWERFEE,RV.BRANCHNAME,RV.REVIEWERKEY,RK.RANKNAME,SHP.SHIPPINGNAME,ED.ENDORSERFULL,rv.DATEENROLL,RV.REBATES' +
            ' FROM REVIEWER RV' +
            ' left join SHIPPING SHP on SHP.SHIPPINGKEY=RV.SHIPPINGKEY' +
            ' left join RANK RK on rk.RANKKEY=rv.RANKKEY' +
            ' left join ENDORSER ED on ED.ENDORSERKEY=rv.ENDORSERKEY' +
            ' WHERE RV.REVIEWERID IS NOT NULL AND RV.STATUS=''A''';

    if RzCheckBox2.Checked then
    begin
        if rzcbPassersForRebates.Checked then
            strSQL:=strSQL+ ' and RV.DATEENROLL between ''' + FormatDateTime('yyyy-mm-dd',rzdatePasserslistBegin.Date) + '''' +
            ' and ''' + FormatDateTime('yyyy-mm-dd',rzdatePasserslistEnd.Date) + ''' and ed.ENDORSERFULL not like ''%walk-in%'''
        else
            strSQL:=strSQL+ ' and RV.DATEPASS between ''' + FormatDateTime('yyyy-mm-dd',rzdatePasserslistBegin.Date) + '''' +
            ' and ''' + FormatDateTime('yyyy-mm-dd',rzdatePasserslistEnd.Date) + '''';
    end;

    IF trim(rzcomboPassersBRanch.Text)<>'' then
        strSQL:=strSQL+
                ' and RV.BRANCHNAME = ''' + TRIM(rzcomboPassersBRanch.Text) + '''';
    if trim(rzcPassersComlist.Text) <>'' then
        strSQL:=strSQL+
                ' and SHP.SHIPPINGNAME = ''' + TRIM(rzcPassersComlist.Text) + '''';
    if Trim(rzeditFullName.Text) <>'' then
        strSQL:=strSQL+
                ' and (UPPER(RV.LASTNAME) + '', '' + UPPER(RV.FIRSTNAME)) like ''%' + TRIM(rzeditFullName.Text) + '%''';

   with TADOQuery.Create(nil) do
   try
     Connection := self.ADOConn;
     SQL.Text := strSQL + ' ORDER BY rv.DATEENROLL';

     try
       Open;
     except
       Exit;
     end;

       With gridPassersResult do
       begin
         Clear;
         RowCount:=2;
         ColCount:=8;
         First;
         iRowCounter:=1;
         Cells[0,0] := 'Rank';
         Cells[1,0] := 'Name';
         Cells[2,0] := 'Status';
         Cells[3,0] := 'Email';
         Cells[4,0] := 'Branch';
         Cells[5,0] := 'Date Enroll';
         Cells[6,0] := 'Endorser';
         Cells[7,0] := 'Tuition Fee';
         ColWidths[0] := 75;
         ColWidths[1] := 175;
         ColWidths[2] := 60;
         ColWidths[3] := 200;
         ColWidths[4] := 100;
         ColWidths[5] := 75;
         ColWidths[6] := 175;
         ColWidths[7] := 80;         

         if not IsEmpty then
         begin
           while not Eof do
           begin
           IF (TRIM(FieldByName('REBATES').AsString)='Y') and (RzCheckBox2.Checked) then
           begin
            next;
           end else
           begin
             if iRowCounter >1 then AddRow;
             Cells[0,iRowCounter] := TRIM(FieldByName('RANKNAME').AsString);
             Cells[1,iRowCounter] := TRIM(FieldByName('NAME').AsString);
             Cells[2,iRowCounter] := TRIM(FieldByName('REVSTATUS').AsString);
             Cells[3,iRowCounter] := TRIM(FieldByName('EMAIL').AsString);
             Cells[4,iRowCounter] := TRIM(FieldByName('BRANCHNAME').AsString);
             Cells[5,iRowCounter] :=FormatDateTime('MM-DD-YYYY',FieldByName('DATEENROLL').AsDateTime);
             Cells[6,iRowCounter] := TRIM(FieldByName('ENDORSERFULL').AsString);
             Cells[7,iRowCounter] := FormatFloat('#,##0.00',FieldByName('REVIEWERFEE').AsVariant);
             Cells[8,iRowCounter] := TRIM(FieldByName('REVIEWERKEY').AsString);
             Next;
             iRowCounter:=iRowCounter+1;
           end;
           end;
         end;
       end;

     finally
       Free;
     end;

end;

procedure TfrmRegistrationMain.rzcPassersComlistSelect(Sender: TObject);
begin
    SetPassersGrid;
end;

procedure TfrmRegistrationMain.TabSheet10Show(Sender: TObject);
begin
    IncShippingList2BillToDropdown(0,'');
end;

procedure TfrmRegistrationMain.rzeditFullNameKeyPress(Sender: TObject;
  var Key: Char);
begin
    SetPassersGrid;
end;

procedure TfrmRegistrationMain.dsReviewerTableDataChange(Sender: TObject;
  Field: TField);
begin
    rzdatetimedatepass.Enabled:= (trim(adoReviewerTable.FieldByName('REVSTATUS').AsString)= 'PASSED')
end;

procedure TfrmRegistrationMain.RzBitBtn5Click(Sender: TObject);
begin
    SetPassersGrid;
end;

procedure TfrmRegistrationMain.RzCheckBox2Click(Sender: TObject);
begin
    rzdatePasserslistBegin.Enabled:=(RzCheckBox2.Checked);
    rzdatePasserslistend.Enabled:=(RzCheckBox2.Checked);
end;

procedure TfrmRegistrationMain.rzcbPassersForRebatesClick(Sender: TObject);
begin
    btnForRebatesPayment.Enabled:=(rzcbPassersForRebates.Checked);
    rzcbSelectAllPassers.Enabled:=(rzcbPassersForRebates.Checked);
end;

procedure TfrmRegistrationMain.btnForRebatesPaymentClick(Sender: TObject);
function DynamicTableUpdatefn(sTableName:string;sTablePK:string;sUpdateFName:string;iPKVal:integer;iUpdateFType:integer;sUpdateFValue:string):boolean;
begin

      with TADOCommand.Create(nil) do
      try
        Connection :=  self.ADOConn;
        CommandText := 'EXEC PROC_CG_UPDATE_TABLE_PROC ''' + sTableName + ''',''' + sTablePK + ''',''' + sUpdateFName + ''',' + inttostr(iPKVal) + ',' + inttostr(iUpdateFType) + ',''' + sUpdateFValue + '''';
        try
            Execute;
            Result:=True;
        except
            Result:=False;
        end;
      finally
        Free;
      end;

end;
var
    i:integer;
    bUpdateResult:BOOLEAN;
begin

    IF rzcbSelectAllPassers.Checked THEN
    BEGIN
        for i:=1 to gridPassersResult.RowCount-1 do
        begin
            bUpdateResult:=DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','SELECTED', strtoint(gridPassersResult.Cells[8,i]), 2,'Y');
            //ShowMessage(gridPassersResult.Cells[8,i]);
        end;
    END
    ELSE
       bUpdateResult:=DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','SELECTED', strtoint(gridPassersResult.Cells[8,i]), 2,'Y');
    //btn_processRebates.SetFocus;
    RzPageControl1.ActivePageIndex:=6;
    //TabSheet7Show(Sender);
end;

procedure TfrmRegistrationMain.TabSheet7Show(Sender: TObject);
var
iRowCounter:integer;
begin

   with TADOQuery.Create(nil) do
   try
     Connection := self.ADOConn;
     SQL.Text := 'SELECT (UPPER(RV.LASTNAME) + '', '' + UPPER(RV.FIRSTNAME)) as NAME,RV.DATEENROLL,ED.ENDORSERFULL' +
            ',RK.RANKNAME,RV.REVIEWERFEE,RV.REVIEWERKEY' +
            ' FROM REVIEWER RV' +
            ' left join ENDORSER ED on ED.ENDORSERKEY=rv.ENDORSERKEY' +
            ' left join RANK RK on RK.RANKKEY=rv.RANKKEY' +
            ' WHERE rv.SELECTED=''Y''';
     try
       Open;
     except
       Exit;
     end;

       With gridRebatesForPayment do
       begin
         Clear;
         RowCount:=2;
         ColCount:=6;
         First;
         iRowCounter:=1;
         Cells[0,0] := 'DATE OF ENROLLMENT';
         Cells[1,0] := 'ENDORSER';
         Cells[2,0] := 'STUDENT';
         Cells[3,0] := 'RANK';
         Cells[4,0] := 'TUITION FEE';
         Cells[5,0] := 'AMOUNT';
         ColWidths[0] := 100;
         ColWidths[1] := 150;
         ColWidths[2] := 150;
         ColWidths[3] := 75;
         ColWidths[4] := 150;
         ColWidths[5] := 150;

         if not IsEmpty then
         begin
           while not Eof do
           begin
             if iRowCounter >1 then AddRow;
             Cells[0,iRowCounter] := FormatDateTime('MM-DD-YYYY',FieldByName('DATEENROLL').AsDateTime);
             Cells[1,iRowCounter] := TRIM(FieldByName('ENDORSERFULL').AsString);;
             Cells[2,iRowCounter] := TRIM(FieldByName('NAME').AsString);
             Cells[3,iRowCounter] := TRIM(FieldByName('RANKNAME').AsString);
             Cells[4,iRowCounter] := FormatFloat('#,##0.00',FieldByName('REVIEWERFEE').AsVariant);
             Cells[5,iRowCounter] := FormatFloat('#,##0.00',1000);
             Cells[6,iRowCounter] := TRIM(FieldByName('REVIEWERKEY').AsString);
             Next;
             iRowCounter:=iRowCounter+1;
           end;
         end;
       end;

     finally
       Free;
     end;

end;
procedure TfrmRegistrationMain.RzBitBtn8Click(Sender: TObject);
function DynamicTableUpdatefn(sTableName:string;sTablePK:string;sUpdateFName:string;iPKVal:integer;iUpdateFType:integer;sUpdateFValue:string):boolean;
begin

      with TADOCommand.Create(nil) do
      try
        Connection :=  self.ADOConn;
        CommandText := 'EXEC PROC_CG_UPDATE_TABLE_PROC ''' + sTableName + ''',''' + sTablePK + ''',''' + sUpdateFName + ''',' + inttostr(iPKVal) + ',' + inttostr(iUpdateFType) + ',''' + sUpdateFValue + '''';
        try
            Execute;
            Result:=True;
        except
            Result:=False;
        end;
      finally
        Free;
      end;

end;
var
    i:integer;
    bUpdateResult:BOOLEAN;
begin
    if gridRebatesForPayment.RealRow>0 then
    begin
     bUpdateResult:=DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','SELECTED', strtoint(gridRebatesForPayment.Cells[6,gridRebatesForPayment.RealRow]), 2,'N');
     gridRebatesForPayment.RemoveSelectedRows;
    end;
end;

procedure TfrmRegistrationMain.RzBitBtn10Click(Sender: TObject);
begin
     TabSheet7Show(Sender);
end;

procedure TfrmRegistrationMain.RzBitBtn6Click(Sender: TObject);
begin
    rzcbPassersForRebates.Checked:=True;
    RzPageControl1.ActivePageIndex:=8;
    iPostData:=True;

end;

procedure TfrmRegistrationMain.btn_processRebatesClick(Sender: TObject);
function DynamicTableUpdatefn(sTableName:string;sTablePK:string;sUpdateFName:string;iPKVal:integer;iUpdateFType:integer;sUpdateFValue:string):boolean;
begin

      with TADOCommand.Create(nil) do
      try
        Connection :=  self.ADOConn;
        CommandText := 'EXEC PROC_CG_UPDATE_TABLE_PROC ''' + sTableName + ''',''' + sTablePK + ''',''' + sUpdateFName + ''',' + inttostr(iPKVal) + ',' + inttostr(iUpdateFType) + ',''' + sUpdateFValue + '''';
        try
            Execute;
            Result:=True;
        except
            Result:=False;
        end;
      finally
        Free;
      end;

end;
var
    i:integer;
    bUpdateResult:BOOLEAN;
begin

    for i:=1 to gridRebatesForPayment.RowCount-1 do
    begin
        bUpdateResult:=DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','SELECTED', strtoint(gridRebatesForPayment.Cells[6,i]), 2,'N');
        bUpdateResult:=DynamicTableUpdatefn('REVIEWER','REVIEWERKEY','REBATES', strtoint(gridRebatesForPayment.Cells[6,i]), 2,'Y');
        //ShowMessage(gridPassersResult.Cells[8,i]);
    end;

    QuickRep4.Preview;
end;


procedure TfrmRegistrationMain.gridRebatesForPaymentGetAlignment(
  Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment;
  var VAlign: TVAlignment);
begin
    if (ACol=4) or (ACol=5) then HAlign:= taRightJustify;
end;

procedure TfrmRegistrationMain.RzBitBtn9Click(Sender: TObject);
var
i:integer;
begin
        with TADOQuery.Create(nil) do
        try
          Connection := self.ADOConn;
          SQL.Text := 'select * from reviewer where branchname=''Manila'' and reviewerkey>7049 order by 1';
          try
            Open;
          except
            Exit;
          end;
          if not IsEmpty then
          begin
            i:=1400899;
            First;
            while not Eof do
            begin
               i:=i+1;
               Edit;
               FieldByName('reviewerid').AsInteger:=i;
               Post;
               next;
            end;
          end;
        finally
          Free;
        end;

end;

end.


